Example #1
0
 private CronTrigger createTrigger(final String cronExpression) {
   CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
   if (configService.isMisfire()) {
     cronScheduleBuilder = cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed();
   } else {
     cronScheduleBuilder = cronScheduleBuilder.withMisfireHandlingInstructionDoNothing();
   }
   return TriggerBuilder.newTrigger()
       .withIdentity(
           Joiner.on("_").join(jobConfiguration.getJobName(), CRON_TRIGGER_INDENTITY_SUFFIX))
       .withSchedule(cronScheduleBuilder)
       .build();
 }
 /**
  * 创建触发器
  *
  * @param cronExpression
  * @return
  */
 private CronTrigger createTrigger(final String cronExpression) {
   CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
   return TriggerBuilder.newTrigger()
       .withIdentity(jobConfiguration.getJobName())
       .withSchedule(cronScheduleBuilder)
       .build();
 }
Example #3
0
  private void scheduleCronJob(String cronString, String elementId) {
    try {
      SchedulerFactory schedulerFactory = new StdSchedulerFactory();
      scheduler = schedulerFactory.getScheduler();
      scheduler.start();

      JobDataMap dataMap = new JobDataMap();
      dataMap.put("trigger", this);

      jobName = "TriggerJob_" + elementId;
      JobDetail job =
          org.quartz.JobBuilder.newJob(CronEventTrigger.class)
              .withIdentity(jobName, jobGroup)
              .usingJobData(dataMap)
              .build();

      Trigger trigger =
          org.quartz.TriggerBuilder.newTrigger()
              .withIdentity("TriggerJob_" + elementId, jobGroup)
              .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
              .build();

      scheduler.scheduleJob(job, trigger);

    } catch (SchedulerException e) {
      log.error(
          "Error while instantiating quartz scheduler for trigger '"
              + triggerDefinition.getId()
              + "',"
              + e.getMessage(),
          e);
    }
  }
  @Test
  public void serialization() {
    String cron = "0/5 * * * * ?";
    CronTrigger trigger =
        TriggerBuilder.newTrigger()
            .forJob("testJob", "testGroup")
            .withIdentity("testTrigger", "testTriggerGroup")
            .withSchedule(CronScheduleBuilder.cronSchedule(cron))
            .usingJobData("timeout", 5)
            .withDescription("A description!")
            .build();

    Map<String, String> triggerMap =
        mapper.convertValue(trigger, new TypeReference<HashMap<String, String>>() {});

    assertThat(triggerMap, hasKey("name"));
    assertEquals("testTrigger", triggerMap.get("name"));
    assertThat(triggerMap, hasKey("group"));
    assertEquals("testTriggerGroup", triggerMap.get("group"));
    assertThat(triggerMap, hasKey("jobName"));
    assertEquals("testJob", triggerMap.get("jobName"));

    CronTriggerImpl cronTrigger = mapper.convertValue(triggerMap, CronTriggerImpl.class);

    assertEquals(trigger.getKey().getName(), cronTrigger.getKey().getName());
    assertEquals(trigger.getKey().getGroup(), cronTrigger.getKey().getGroup());
    assertEquals(trigger.getStartTime(), cronTrigger.getStartTime());
    assertEquals(trigger.getCronExpression(), cronTrigger.getCronExpression());
    assertEquals(trigger.getTimeZone(), cronTrigger.getTimeZone());
  }
 /** This method adds the {@link #JOBKEY_DATABASE_UPDATE_REGULAR} job to the scheduler. */
 public void startRegularDatabaseUpdates() {
   try {
     Trigger trigger = null;
     switch (period) {
       case ServiceConstants.PARAM_VALUE_DAILY:
         trigger =
             TriggerBuilder.newTrigger()
                 .forJob(regularDatabaseUpdateJob)
                 .startNow()
                 .withSchedule(
                     CronScheduleBuilder.dailyAtHourAndMinute(atHour, 0)
                         .withMisfireHandlingInstructionFireAndProceed())
                 .build();
         break;
       case ServiceConstants.PARAM_VALUE_WEEKLY:
         trigger =
             TriggerBuilder.newTrigger()
                 .forJob(regularDatabaseUpdateJob)
                 .startNow()
                 .withSchedule(
                     CronScheduleBuilder.weeklyOnDayAndHourAndMinute(dayOfWeek, atHour, 0)
                         .withMisfireHandlingInstructionFireAndProceed())
                 .build();
         break;
       case ServiceConstants.PARAM_VALUE_MONTHLY:
         trigger =
             TriggerBuilder.newTrigger()
                 .forJob(regularDatabaseUpdateJob)
                 .startNow()
                 .withSchedule(
                     CronScheduleBuilder.monthlyOnDayAndHourAndMinute(dayOfMonth, atHour, 0)
                         .withMisfireHandlingInstructionFireAndProceed())
                 .build();
         break;
       default:
         throw new WebApplicationException(
             Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                 .entity(
                     "Could not initialize trigger for regular database update. Period was not set")
                 .build());
     }
     sched.scheduleJob(trigger);
   } catch (SchedulerException ex) {
     Logger.getLogger(QuartzSchedulerController.class.getName()).log(Level.SEVERE, null, ex);
     throw new WebApplicationException(PreparedServerResponses.ERROR_SCHEDULER);
   }
 }
 private void registerJob(
     Class<? extends Job> jobClass, String cronExpression, Map<String, String> params)
     throws SchedulerException {
   LOG.debug("Registrando job {} con la expresion cron {}", jobClass.getName(), cronExpression);
   if (params != null) {
     for (String key : params.keySet()) {
       String contextKey = jobClass.getName() + "." + key;
       scheduler.getContext().put(contextKey, params.get(key));
     }
   }
   String name = jobClass.getName();
   JobDetail jobDetail =
       JobBuilder.newJob(jobClass).withDescription(name).withIdentity(name).build();
   CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
   MutableTrigger trigger = scheduleBuilder.build();
   trigger.setKey(new TriggerKey(name));
   scheduler.scheduleJob(jobDetail, trigger);
 }
  public static void main(String[] args) throws Exception {

    JobKey jobKeyA = new JobKey("jobA", "group1");
    JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity(jobKeyA).build();

    JobKey jobKeyB = new JobKey("jobB", "group1");
    JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity(jobKeyB).build();

    JobKey jobKeyC = new JobKey("jobC", "group1");
    JobDetail jobC = JobBuilder.newJob(JobC.class).withIdentity(jobKeyC).build();

    Trigger trigger1 =
        TriggerBuilder.newTrigger()
            .withIdentity("dummyTriggerName1", "group1")
            .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
            .build();

    Trigger trigger2 =
        TriggerBuilder.newTrigger()
            .withIdentity("dummyTriggerName2", "group1")
            .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
            .build();

    Trigger trigger3 =
        TriggerBuilder.newTrigger()
            .withIdentity("dummyTriggerName3", "group1")
            .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
            .build();

    StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
    schedulerFactory.initialize("resources/quartz.properties");
    Scheduler scheduler = schedulerFactory.getScheduler();

    scheduler.start();
    //    	scheduler.scheduleJob(jobA, trigger1);
    //    	scheduler.scheduleJob(jobB, trigger2);
    //    	scheduler.scheduleJob(jobC, trigger3);

    scheduler.deleteJob(jobKeyA);
    //    	scheduler.pauseJob(jobKeyB);
    scheduler.resumeJob(jobKeyB);
  }
 @SuppressWarnings("unchecked")
 public void cron(String cron, Class<?> klass) throws SchedulerException {
   String name = klass.getName();
   JobDetail job = JobBuilder.newJob((Class<? extends Job>) klass).withIdentity(name).build();
   CronTrigger trigger =
       TriggerBuilder.newTrigger()
           .withIdentity(name)
           .withSchedule(CronScheduleBuilder.cronSchedule(cron))
           .build();
   scheduler.scheduleJob(job, trigger);
 }
Example #9
0
  public Registration run() throws Exception {

    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    final Scheduler scheduler = schedulerFactory.getScheduler();
    scheduler.setJobFactory(jobFactory.get());
    for (Job j : jobProvider.get()) {

      JobDetail jobDetail =
          JobBuilder.newJob(j.getClass())
              .withIdentity(j.getClass().getSimpleName() + "Job")
              .build();

      if (shouldInstall(j.getClass())) {
        ScheduleInterval interval = j.getClass().getAnnotation(ScheduleInterval.class);
        if (interval != null) {
          Trigger trigger =
              TriggerBuilder.newTrigger()
                  .withIdentity(j.getClass().getSimpleName() + "TriggerId")
                  .withSchedule(
                      SimpleScheduleBuilder.simpleSchedule()
                          .withIntervalInSeconds(interval.value())
                          .repeatForever())
                  .build();
          System.out.println(
              "Schedule " + j.getClass().getSimpleName() + " @ " + interval.value() + "sec");
          scheduler.scheduleJob(jobDetail, trigger);
        }

        CronInterval cron = j.getClass().getAnnotation(CronInterval.class);
        if (cron != null) {
          Trigger trigger =
              TriggerBuilder.newTrigger()
                  .withIdentity(j.getClass().getSimpleName() + "TriggerId")
                  .withSchedule(CronScheduleBuilder.cronSchedule(cron.value()))
                  .build();
          System.out.println("Schedule " + j.getClass().getSimpleName() + " @ " + cron.value());
          scheduler.scheduleJob(jobDetail, trigger);
        }
      }
    }

    scheduler.start();
    return new Registration() {
      public void unregister() {
        try {
          scheduler.shutdown();
        } catch (Exception e) {
        }
        System.out.println("Schedular Stopped");
      }
    };
  }
  private void scheduleAllJobsWithOnAnnotation() throws SchedulerException {
    List<Class<? extends Job>> onJobClasses = getJobClasses(On.class);
    log.info("Jobs with @On annotation: " + onJobClasses);

    for (Class<? extends org.quartz.Job> clazz : onJobClasses) {
      On annotation = clazz.getAnnotation(On.class);

      CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(annotation.value());
      Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).build();
      JobBuilder jobBuilder = JobBuilder.newJob(clazz);
      scheduler.scheduleJob(jobBuilder.build(), trigger);
    }
  }
Example #11
0
  public void refreshCron(String id) {
    removeCron(id);
    synchronized (notes) {
      Note note = notes.get(id);
      if (note == null) {
        return;
      }
      Map<String, Object> config = note.getConfig();
      if (config == null) {
        return;
      }

      String cronExpr = (String) note.getConfig().get("cron");
      if (cronExpr == null || cronExpr.trim().length() == 0) {
        return;
      }

      JobDetail newJob =
          JobBuilder.newJob(CronJob.class)
              .withIdentity(id, "note")
              .usingJobData("noteId", id)
              .build();

      Map<String, Object> info = note.getInfo();
      info.put("cron", null);

      CronTrigger trigger = null;
      try {
        trigger =
            TriggerBuilder.newTrigger()
                .withIdentity("trigger_" + id, "note")
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpr))
                .forJob(id, "note")
                .build();
      } catch (Exception e) {
        logger.error("Error", e);
        info.put("cron", e.getMessage());
      }

      try {
        if (trigger != null) {
          quartzSched.scheduleJob(newJob, trigger);
        }
      } catch (SchedulerException e) {
        logger.error("Error", e);
        info.put("cron", "Scheduler Exception");
      }
    }
  }
Example #12
0
  public boolean start() {

    try {
      scheduler.start();
    } catch (SchedulerException e) {
      throw new SynapseException("Error starting the scheduler", e);
    }

    Trigger trigger;
    TriggerBuilder<Trigger> triggerBuilder = newTrigger().withIdentity(name + "-trigger");

    if (cronExpression == null || "".equals(cronExpression)) {
      trigger =
          triggerBuilder
              .withSchedule(
                  simpleSchedule()
                      .withIntervalInMilliseconds(interval)
                      .repeatForever()
                      .withMisfireHandlingInstructionNextWithRemainingCount())
              .build();
    } else {
      trigger =
          triggerBuilder
              .startNow()
              .withSchedule(
                  CronScheduleBuilder.cronSchedule(cronExpression)
                      .withMisfireHandlingInstructionDoNothing())
              .build();
    }

    JobDataMap jobDataMap = getJobDataMap();
    jobDataMap.put(MessageProcessorConstants.PARAMETERS, parameters);

    JobBuilder jobBuilder = getJobBuilder();
    JobDetail jobDetail = jobBuilder.usingJobData(jobDataMap).build();

    try {
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      throw new SynapseException(
          "Error scheduling job : " + jobDetail + " with trigger " + trigger, e);
    }
    if (logger.isDebugEnabled()) {
      logger.debug("Started message processor. [" + getName() + "].");
    }

    return true;
  }
Example #13
0
  public static void main(String[] args) throws SchedulerException, IOException {
    Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    JobDetail jobDetail = JobBuilder.newJob(TestJob.class).withIdentity("sample").build();
    Trigger trigger =
        TriggerBuilder.newTrigger()
            .withIdentity("sample")
            .forJob(jobDetail)
            .withSchedule(CronScheduleBuilder.cronSchedule("*/5,*/3 * * * * ? *"))
            .build();
    scheduler.scheduleJob(jobDetail, trigger);

    System.out.print("Press enter to exit");
    scheduler.start();
    System.in.read();
    scheduler.shutdown();
  }
 void startJob(QuartzJob job) {
   assertNotNull(job, "任务不存在");
   JobKey key = createJobKey(job.getId());
   JobDetail jobDetail =
       JobBuilder.newJob(SimpleJob.class)
           .withIdentity(key)
           .setJobData(createJobDataMap(job.getParameters()))
           .usingJobData(SimpleJobFactory.QUARTZ_ID_KEY, job.getId())
           .withDescription(job.getName() + (job.getRemark() == null ? "" : job.getRemark()))
           .build();
   MutableTrigger trigger = CronScheduleBuilder.cronSchedule(job.getCron()).build();
   trigger.setKey(createTriggerKey(job.getId()));
   try {
     scheduler.scheduleJob(jobDetail, trigger);
   } catch (SchedulerException e) {
     throw new BusinessException("创建定时任务失败!", e, 500);
   }
 }
Example #15
0
 public void schdeuleJob(
     Class jobClass, Scheduler scheduler, JobDetails jobDetails, JobDataMap newJobData)
     throws SchedulerException {
   JobDetail jobdetail =
       JobBuilder.newJob(jobClass)
           .usingJobData(newJobData)
           .withIdentity(jobDetails.getJobName(), jobDetails.getJobName())
           .build();
   Trigger trigger =
       TriggerBuilder.newTrigger()
           .withIdentity(jobDetails.getJobName(), jobDetails.getJobName())
           .withSchedule(
               CronScheduleBuilder.cronSchedule(
                   "" + jobDetails.getScheduler().getSchedulerExpression() + ""))
           .build();
   scheduler.getListenerManager().addJobListener(joblistener);
   scheduler.start();
   scheduler.scheduleJob(jobdetail, trigger);
 }
Example #16
0
  /** {@inheritDoc} */
  @SuppressWarnings("rawtypes")
  public void updated(Dictionary config) throws ConfigurationException {

    if (config != null) {
      String ip = (String) config.get("ip");
      if (StringUtils.isNotBlank(ip)) {
        if (!ip.equals(FritzboxBinding.ip)) {
          // only do something if the ip has changed
          FritzboxBinding.ip = ip;
          conditionalDeActivate();

          // schedule a daily reconnection as sometimes the FritzBox
          // stops sending data
          // and thus blocks the monitor thread
          try {
            Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
            JobDetail job =
                newJob(ReconnectJob.class).withIdentity("Reconnect", "FritzBox").build();

            CronTrigger trigger =
                newTrigger()
                    .withIdentity("Reconnect", "FritzBox")
                    .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 * * ?"))
                    .build();

            sched.scheduleJob(job, trigger);
            logger.debug(
                "Scheduled a daily reconnection to FritzBox on {}", ip + ":" + MONITOR_PORT);
          } catch (SchedulerException e) {
            logger.warn("Could not create daily reconnection job: {}", e.getMessage());
          }
        }
      }
      String password = (String) config.get("password");
      if (StringUtils.isNotBlank(password)) {
        FritzboxBinding.password = password;
      }
    }
  }
  public void start(Long id) throws Exception {
    synchronized (sync) {
      AnomalyFunctionSpec spec = specDAO.findById(id);
      if (spec == null) {
        throw new IllegalArgumentException("No function with id " + id);
      }
      AnomalyFunction anomalyFunction = anomalyFunctionFactory.fromSpec(spec);

      String triggerKey = String.format("scheduled_anomaly_function_trigger_%d", spec.getId());
      CronTrigger trigger =
          TriggerBuilder.newTrigger()
              .withIdentity(triggerKey)
              .withSchedule(CronScheduleBuilder.cronSchedule(spec.getCron()))
              .build();

      String jobKey = String.format("scheduled_anomaly_function_job_%d", spec.getId());
      scheduledJobKeys.put(id, jobKey);

      buildAndScheduleJob(jobKey, trigger, anomalyFunction, spec, null, null); // use schedule time
      // to determine
      // start/end
    }
  }
  /**
   * Creates and schedules a new quartz-job and trigger with model and rule name as jobData.
   *
   * @param rule the rule to schedule
   * @param trigger the defined trigger
   * @throws SchedulerException if there is an internal Scheduler error.
   */
  private void createTimers(String modelName) {
    PersistenceModel persistModel =
        (PersistenceModel) modelRepository.getModel(modelName + ".persist");
    if (persistModel != null) {
      for (Strategy strategy : persistModel.getStrategies()) {
        if (strategy instanceof CronStrategy) {
          CronStrategy cronStrategy = (CronStrategy) strategy;
          String cronExpression = cronStrategy.getCronExpression();
          JobKey jobKey = new JobKey(strategy.getName(), modelName);
          try {
            JobDetail job =
                newJob(PersistItemsJob.class)
                    .usingJobData(
                        PersistItemsJob.JOB_DATA_PERSISTMODEL,
                        cronStrategy.eResource().getURI().trimFileExtension().path())
                    .usingJobData(PersistItemsJob.JOB_DATA_STRATEGYNAME, cronStrategy.getName())
                    .withIdentity(jobKey)
                    .build();

            Trigger quartzTrigger =
                newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();

            scheduler.scheduleJob(job, quartzTrigger);

            logger.debug(
                "Scheduled strategy {} with cron expression {}",
                new Object[] {jobKey.toString(), cronExpression});
          } catch (SchedulerException e) {
            logger.error(
                "Failed to schedule job for strategy {} with cron expression {}",
                new String[] {jobKey.toString(), cronExpression},
                e);
          }
        }
      }
    }
  }
Example #19
0
  public TestTrigger() throws Exception {
    System.out.println("Trigger called");

    JobKey WebDashBoardQuartz = new JobKey("jobA", "group1");
    JobDetail jobWebDashBoardQuartz =
        JobBuilder.newJob(WebDashBoardQuartz.class).withIdentity(WebDashBoardQuartz).build();

    JobKey webResponseAvg = new JobKey("jobB", "group2");
    JobDetail jobWebResponseAvg =
        JobBuilder.newJob(AvgResponsePerMinWeb.class).withIdentity(webResponseAvg).build();

    JobKey avgLive = new JobKey("jobC", "group3");
    JobDetail jobLive =
        JobBuilder.newJob(AndroidAverageCalculation.class).withIdentity(avgLive).build();

    JobKey DashBoardQuartz = new JobKey("jobD", "group4");
    JobDetail jobDashBoardQuartz =
        JobBuilder.newJob(DashBoardQuartz.class).withIdentity(DashBoardQuartz).build();

    JobKey AvgResponsePerMin = new JobKey("jobE", "group5");
    JobDetail jobAvgResponsePerMin =
        JobBuilder.newJob(AvgResponsePerMin.class).withIdentity(AvgResponsePerMin).build();

    JobKey OneDayAggregation = new JobKey("jobF", "group6");
    JobDetail jobOneDayAggregation =
        JobBuilder.newJob(OneDayAggregation.class).withIdentity(OneDayAggregation).build();

    JobKey OneDayAggregationWeb = new JobKey("jobG", "group7");
    JobDetail jobOneDayAggregationWeb =
        JobBuilder.newJob(OneDayAggregationWeb.class).withIdentity(OneDayAggregationWeb).build();

    JobKey WebMapScheduler = new JobKey("jobH", "group8");
    JobDetail jobWebMapScheduler =
        JobBuilder.newJob(WebMapScheduler.class).withIdentity(WebMapScheduler).build();

    JobKey AppMapScheduler = new JobKey("jobI", "group9");
    JobDetail jobAppMapScheduler =
        JobBuilder.newJob(AppMapScheduler.class).withIdentity(AppMapScheduler).build();

    JobKey AndroidVersionBufferScheduler = new JobKey("jobJ", "group10");
    JobDetail jobAndroidVersionBufferScheduler =
        JobBuilder.newJob(AndroidVersionBufferScheduler.class)
            .withIdentity(AndroidVersionBufferScheduler)
            .build();

    JobKey ApplicationVersionBufferScheduler = new JobKey("jobK", "group11");
    JobDetail jobApplicationVersionBufferScheduler =
        JobBuilder.newJob(ApplicationVersionBufferScheduler.class)
            .withIdentity(ApplicationVersionBufferScheduler)
            .build();

    JobKey OneDayAggregationBranch = new JobKey("jobL", "group12");
    JobDetail jobOneDayAggregationBranch =
        JobBuilder.newJob(OneDayAggregationBranch.class)
            .withIdentity(OneDayAggregationBranch)
            .build();

    /*
     * DBCursor alertData = null;
     *
     * try {
     *
     * DBCollection coll1 = db.getCollection("DurationDB"); //
     * //System.out.println("collection name:" + coll1.getName());
     *
     * BasicDBObject findObj = new BasicDBObject(); alertData =
     * coll1.find(findObj); alertData.sort(new BasicDBObject("_id", -1));
     * alertData.limit(1); List<DBObject> dbObjs = alertData.toArray();
     *
     * for (int i = dbObjs.size() - 1; i >= 0; i--)
     *
     * { DBObject txnDataObject = dbObjs.get(i); int averagealerts =
     * (Integer) txnDataObject .get("Average_Alerts"); //
     * //System.out.println("DURATION OF LIVE:" + averagealerts);
     *
     * int inci = (Integer) txnDataObject.get("Incident_Duration"); //
     * //System.out.println("Duration of INCIDENT" + inci);
     *
     * int usagetime = (Integer) txnDataObject.get("Usagetime"); //
     * //System.out.println("Duration of usage" + usagetime);
     */
    // -------Triggers-----------------------------------------//
    Trigger trigger1 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName1", "group1")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();

    Trigger trigger2 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName2", "group2")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0/1 * * * ?"))
            .build();

    Trigger trigger3 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName3", "group3")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();

    Trigger trigger4 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName4", "group4")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();
    Trigger trigger5 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName5", "group5")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0/1 * * * ?"))
            .build();

    Trigger trigger6 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName6", "group6")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 59 23 * * ?"))
            .build();

    Trigger trigger7 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName7", "group7")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 59 23 * * ?"))
            .build();

    Trigger trigger8 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName8", "group8")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();

    Trigger trigger9 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName9", "group9")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();

    Trigger trigger10 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName10", "group10")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0/15 * * * ?"))
            .build();

    Trigger trigger11 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName11", "group11")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0/15 * * * ?"))
            .build();

    Trigger trigger12 =
        TriggerBuilder.newTrigger()
            .withIdentity("TriggerName12", "group12")
            .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?"))
            .build();

    scheduler = new StdSchedulerFactory().getScheduler();
    scheduler.start();

    scheduler.scheduleJob(jobWebDashBoardQuartz, trigger1);
    scheduler.scheduleJob(jobWebResponseAvg, trigger2);
    scheduler.scheduleJob(jobLive, trigger3);
    scheduler.scheduleJob(jobDashBoardQuartz, trigger4);
    scheduler.scheduleJob(jobAvgResponsePerMin, trigger5);
    scheduler.scheduleJob(jobOneDayAggregation, trigger6);
    scheduler.scheduleJob(jobOneDayAggregationWeb, trigger7);
    scheduler.scheduleJob(jobWebMapScheduler, trigger8);
    scheduler.scheduleJob(jobAppMapScheduler, trigger9);
    scheduler.scheduleJob(jobAndroidVersionBufferScheduler, trigger10);
    scheduler.scheduleJob(jobApplicationVersionBufferScheduler, trigger11);
    scheduler.scheduleJob(jobOneDayAggregationBranch, trigger12);

    /* scheduler.shutdown(false); */

  }
  protected Trigger getQuartzTrigger(
      com.liferay.portal.kernel.scheduler.Trigger trigger, StorageType storageType)
      throws SchedulerException {

    if (trigger == null) {
      return null;
    }

    Date endDate = trigger.getEndDate();
    String jobName = fixMaxLength(trigger.getJobName(), _jobNameMaxLength, storageType);
    String groupName = fixMaxLength(trigger.getGroupName(), _groupNameMaxLength, storageType);

    Date startDate = trigger.getStartDate();

    if (startDate == null) {
      startDate = new Date(System.currentTimeMillis());
    }

    TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();

    triggerBuilder.endAt(endDate);
    triggerBuilder.forJob(jobName, groupName);
    triggerBuilder.startAt(startDate);
    triggerBuilder.withIdentity(jobName, groupName);

    TriggerType triggerType = trigger.getTriggerType();

    if (triggerType == TriggerType.CRON) {
      triggerBuilder.withSchedule(
          CronScheduleBuilder.cronSchedule((String) trigger.getTriggerContent()));

      return triggerBuilder.build();
    }

    ObjectValuePair<Integer, TimeUnit> objectValuePair =
        (ObjectValuePair<Integer, TimeUnit>) trigger.getTriggerContent();

    int interval = objectValuePair.getKey();

    if (interval < 0) {
      if (_log.isWarnEnabled()) {
        _log.warn("Not scheduling " + trigger.getJobName() + " because interval is less than 0");
      }

      return null;
    } else if (interval == 0) {
      return triggerBuilder.build();
    }

    TimeUnit timeUnit = objectValuePair.getValue();

    if (timeUnit == TimeUnit.MILLISECOND) {
      SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule();

      simpleScheduleBuilder.withIntervalInMilliseconds(interval);
      simpleScheduleBuilder.withRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);

      triggerBuilder.withSchedule(simpleScheduleBuilder);
    } else {
      CalendarIntervalScheduleBuilder calendarIntervalScheduleBuilder =
          CalendarIntervalScheduleBuilder.calendarIntervalSchedule();

      calendarIntervalScheduleBuilder.withInterval(interval, IntervalUnit.valueOf(timeUnit.name()));

      triggerBuilder.withSchedule(calendarIntervalScheduleBuilder);
    }

    return triggerBuilder.build();
  }
Example #21
0
    /**
     * Refreshes the job schedule with the current list of enabled jobs of the type to be scheduled.
     *
     * @param scheduler The scheduler to update.
     * @return The updated scheduler.
     */
    protected Scheduler _refreshJobSchedule(Scheduler scheduler) {
      _disposeScheduler(scheduler);

      String schedulerName = null;
      Properties props = new Properties();

      // Set quartz worker thread properties
      props.put(
          QUARTZ_THREADPOOL_COUNT,
          _configuration.getValue(
              Property.QUARTZ_THREADPOOL_COUNT.getName(),
              Property.QUARTZ_THREADPOOL_COUNT.getDefaultValue()));
      props.put(QUARTZ_THREAD_PRIORITY, QUARTZ_THREAD_PRIORITY_VALUE);
      props.put(
          StdSchedulerFactory
              .PROP_SCHED_SCHEDULER_THREADS_INHERIT_CONTEXT_CLASS_LOADER_OF_INITIALIZING_THREAD,
          true);

      /* Have multiple scheduler instances for different job types, so that when
       * we stop the previous instance of a scheduler during the refresh cycle it does not affect another scheduler.
       */
      switch (Thread.currentThread().getName()) {
        case "schedule-alerts":
        default:
          schedulerName = "AlertScheduler";
      }
      props.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, schedulerName);

      SchedulerFactory schedulerFactory;
      Scheduler result = null;

      try {
        schedulerFactory = new StdSchedulerFactory(props);
        result = schedulerFactory.getScheduler();
      } catch (Exception e) {
        _logger.error("Exception in setting up scheduler: {}", e);
        return result;
      }
      for (CronJob job : getEnabledJobs()) {
        _logger.debug("Adding job to scheduler: {}", job);
        try {
          // Convert from linux cron to quartz cron expression
          String quartzCronEntry =
              "0 " + job.getCronEntry().substring(0, job.getCronEntry().length() - 1) + "?";
          JobDetail jobDetail = JobBuilder.newJob(RunnableJob.class).build();
          CronTrigger cronTrigger =
              TriggerBuilder.newTrigger()
                  .withSchedule(CronScheduleBuilder.cronSchedule(quartzCronEntry))
                  .build();

          // Pass parameter to quartz worker threads
          jobDetail.getJobDataMap().put(RunnableJob.CRON_JOB, job);
          jobDetail.getJobDataMap().put(RunnableJob.LOCK_TYPE, lockType);
          jobDetail.getJobDataMap().put("AlertService", _alertService);
          jobDetail.getJobDataMap().put("AuditService", _auditService);
          result.scheduleJob(jobDetail, cronTrigger);
        } catch (Exception ex) {
          String msg = "Failed to schedule job {0} : {1}";
          JPAEntity entity = JPAEntity.class.cast(job);

          _auditService.createAudit(msg, entity, entity, ex.getMessage());
          _logger.error("Failed to schedule job {} : {}", job, ex.getMessage());
        }
      }
      try {
        result.start();
      } catch (SchedulerException e) {
        _logger.error("Exception in starting scheduler: {}", e);
      }
      _logger.info("Job schedule refreshed.");
      return result;
    }
  /** Loads jobs and schedules triggers for preconfigured jobs. */
  private void loadInitialSchedules() {
    for (SpringInitialJobSchedule sched : getInitialJobSchedules()) {
      SpringJobBeanWrapper wrapper = sched.getJobBeanWrapper();

      LOG.debug("Loading schedule for preconfigured job \"" + wrapper.getJobType() + "\"");

      JobDetail jd =
          JobBuilder.newJob(wrapper.getJobClass())
              .withIdentity(sched.getJobName(), Scheduler.DEFAULT_GROUP)
              .storeDurably()
              .requestRecovery()
              .build();

      JobDataMap map = jd.getJobDataMap();

      map.put(JobBeanWrapper.SPRING_BEAN_NAME, wrapper.getBeanId());
      map.put(JobBeanWrapper.JOB_TYPE, wrapper.getJobType());

      if (SpringConfigurableJobBeanWrapper.class.isAssignableFrom(wrapper.getClass())) {
        SpringConfigurableJobBeanWrapper confJob = (SpringConfigurableJobBeanWrapper) wrapper;
        ConfigurableJobPropertyValidator validator = confJob.getConfigurableJobPropertyValidator();
        Map<String, String> conf = sched.getConfiguration();
        boolean fail = false;

        for (ConfigurableJobProperty cProp : confJob.getConfigurableJobProperties()) {
          String key = cProp.getLabelResourceKey(), val = conf.get(key);

          LOG.debug("job property '" + key + "' is set to '" + val + "'");

          if (val == null && cProp.isRequired()) {
            val = cProp.getDefaultValue();

            if (val == null) {
              LOG.error(
                  "job property '"
                      + key
                      + "' is required but has no value; job '"
                      + sched.getJobName()
                      + "' of type '"
                      + wrapper.getJobClass()
                      + "' will not be configured");

              fail = true;
              break;
            }

            LOG.debug("job property '" + key + "' set to default value '" + val + "'");
          }

          if (val != null) {

            try {
              validator.assertValid(key, val);
            } catch (ConfigurableJobPropertyValidationException cjpve) {
              LOG.error(
                  "job property '"
                      + key
                      + "' was set to an invalid value '"
                      + val
                      + "'; job '"
                      + sched.getJobName()
                      + "' of type '"
                      + wrapper.getJobClass()
                      + "' will not be configured");

              fail = true;
              break;
            }

            map.put(key, val);
          }
        }
        if (fail) continue;
      }

      try {
        scheduler.addJob(jd, false);
      } catch (SchedulerException e) {
        LOG.error(
            "Failed to schedule job '"
                + sched.getJobName()
                + "' of type '"
                + wrapper.getJobClass()
                + "'");
        continue;
      }

      Trigger trigger = null;
      trigger =
          TriggerBuilder.newTrigger()
              .withIdentity(sched.getTriggerName(), Scheduler.DEFAULT_GROUP)
              .forJob(jd.getKey())
              .withSchedule(CronScheduleBuilder.cronSchedule(sched.getCronExpression()))
              .build();

      try {
        scheduler.scheduleJob(trigger);
      } catch (SchedulerException e) {
        LOG.error(
            "Trigger could not be scheduled. Failed to schedule job '"
                + sched.getJobName()
                + "' of type '"
                + wrapper.getJobClass()
                + "'");
      }
    }
  }
  private void registerJob(
      final String jobName,
      final Job jobInstance,
      final String cronExpression,
      final Date startAt,
      final Map<String, Object> jobMap)
      throws SchedulerException, ParseException {

    synchronized (scheduler.getScheduler()) {
      boolean jobAlreadyRunning = false;
      for (JobExecutionContext jobCtx : scheduler.getScheduler().getCurrentlyExecutingJobs()) {
        if (jobName.equals(jobCtx.getJobDetail().getKey().getName())
            && Scheduler.DEFAULT_GROUP.equals(jobCtx.getJobDetail().getKey().getGroup())) {

          jobAlreadyRunning = true;

          LOG.debug("Job {} already running, cancel", jobCtx.getJobDetail().getKey());
        }
      }

      if (jobAlreadyRunning) {
        return;
      }
    }

    // 0. unregister job
    unregisterJob(jobName);

    // 1. Job bean
    ApplicationContextProvider.getBeanFactory().registerSingleton(jobName, jobInstance);

    // 2. JobDetail bean
    JobBuilder jobDetailBuilder =
        JobBuilder.newJob(jobInstance.getClass())
            .withIdentity(jobName)
            .usingJobData(new JobDataMap(jobMap));

    // 3. Trigger
    if (cronExpression == null && startAt == null) {
      // Jobs added with no trigger must be durable
      scheduler.getScheduler().addJob(jobDetailBuilder.storeDurably().build(), true);
    } else {
      TriggerBuilder<?> triggerBuilder;

      if (cronExpression == null) {
        triggerBuilder =
            TriggerBuilder.newTrigger()
                .withIdentity(JobNamer.getTriggerName(jobName))
                .startAt(startAt);
      } else {
        triggerBuilder =
            TriggerBuilder.newTrigger()
                .withIdentity(JobNamer.getTriggerName(jobName))
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression));

        if (startAt == null) {
          triggerBuilder = triggerBuilder.startNow();
        } else {
          triggerBuilder = triggerBuilder.startAt(startAt);
        }
      }

      scheduler.getScheduler().scheduleJob(jobDetailBuilder.build(), triggerBuilder.build());
    }
  }