Exemplo n.º 1
0
  public void quartzTest() throws Exception {

    JobDetail jobDetail =
        JobBuilder.newJob(QuartsDemo.class).withIdentity("testJob_1", "group_1").build();

    Trigger trigger =
        TriggerBuilder.newTrigger()
            .withIdentity("trigger_1", "group_1")
            .startNow()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(1) // 时间间隔
                    .withRepeatCount(10) // 重复次数(将执行 10 次/ or //调用10次)
                )
            .build();
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    sched.scheduleJob(jobDetail, trigger);

    sched.start();

    Thread.currentThread().sleep(20000);

    System.err.println("关闭  ");
    sched.shutdown();
  }
 /** 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 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);
    }
  }
  private void scheduleAllJobsWithEveryAnnotation() throws SchedulerException {
    List<Class<? extends Job>> everyJobClasses = getJobClasses(Every.class);
    log.info("Jobs with @Every annotation: " + everyJobClasses);

    for (Class<? extends org.quartz.Job> clazz : everyJobClasses) {
      Every annotation = clazz.getAnnotation(Every.class);
      int secondDelay = TimeParserUtil.parseDuration(annotation.value());
      SimpleScheduleBuilder scheduleBuilder =
          SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(secondDelay).repeatForever();
      Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).build();

      JobBuilder jobBuilder = JobBuilder.newJob(clazz);
      scheduler.scheduleJob(jobBuilder.build(), trigger);
    }
  }
Exemplo n.º 5
0
  public static void main(String[] args) {
    // Configure Job
    JobDetail jobDetail =
        JobBuilder.newJob(HelloWorldJob.class).withIdentity("HelloWorldJob").build();

    // Configure Trigger
    Trigger trigger =
        TriggerBuilder.newTrigger()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
            .build();

    // Start Scheduler
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    try {
      Scheduler scheduler = schedulerFactory.getScheduler();
      scheduler.start();
      scheduler.scheduleJob(jobDetail, trigger);
    } catch (SchedulerException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 6
0
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);
    ServletContext ctx = sce.getServletContext();
    StdSchedulerFactory factory = (StdSchedulerFactory) ctx.getAttribute(QUARTZ_FACTORY_KEY);
    try {
      Scheduler scheduler = factory.getScheduler();
      JobDetail jobDetail = JobBuilder.newJob(SchedulerJob.class).build();

      Trigger trigger =
          TriggerBuilder.newTrigger()
              .withIdentity("simple", "group1")
              .startNow()
              .withSchedule(
                  SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(10).repeatForever())
              .build();

      scheduler.scheduleJob(jobDetail, trigger);
      scheduler.start();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("There was an error scheduling the job." + e.getMessage());
    }
  }
 /**
  * Builds a Trigger which fires the Job identified by {@code jobKey} at (or around) the given
  * {@code triggerDateTime}.
  *
  * @param triggerDateTime The time at which a trigger was requested
  * @param jobKey The key of the job to be triggered
  * @return a configured Trigger for the Job with key {@code jobKey}
  */
 protected Trigger buildTrigger(Instant triggerDateTime, JobKey jobKey) {
   return TriggerBuilder.newTrigger().forJob(jobKey).startAt(Date.from(triggerDateTime)).build();
 }
 private Trigger executeNowTrigger() {
   return TriggerBuilder.newTrigger().startNow().build();
 }
Exemplo n.º 9
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;
    }