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();
  }
示例#2
0
    private void _disposeScheduler(Scheduler scheduler) {
      if (scheduler != null) {
        try {
          scheduler.shutdown();

          /* Add a small sleep so Tomcat does not complain - the web application has started a thread,
           * but has failed to stop it.This is very likely to create a memory leak.
           */
          Thread.sleep(2000);
        } catch (SchedulerException e) {
          _logger.error("Quartz failed to shutdown {}", e);
        } catch (InterruptedException e) {
          _logger.warn("Shutdown of quartz scheduler was interrupted.");
          Thread.currentThread().interrupt();
        }
      }
    }
  public void runQuarts() throws Exception {
    // 定时任务 ,分组名称信息,分组名 如果不设置分组名 是默认分组Default

    JobDetail jobDetail = new JobDetailImpl("myJobName", "myJobGroupName", QuartsDemo.class);

    // 设置触发器
    SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl("myTiggerName");

    // 触发器 从当前时间开始
    simpleTrigger.setStartTime(new Date());
    // 调用10次
    simpleTrigger.setRepeatCount(10);
    // 每隔2000毫秒 / 2秒
    simpleTrigger.setRepeatInterval(1000);
    // 定义调度
    Scheduler scheudle = new StdSchedulerFactory().getScheduler();
    scheudle.scheduleJob(jobDetail, simpleTrigger);
    // 调度启动
    scheudle.start();
    Thread.currentThread().sleep(10000);
    // 调度关闭
    System.err.println("关闭  ");
    scheudle.shutdown();
  }
示例#4
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;
    }