예제 #1
0
 @Override
 @Transactional
 public synchronized void startAlertScheduling() {
   requireNotDisposed();
   if (_alertSchedulingThread != null && _alertSchedulingThread.isAlive()) {
     _logger.info("Request to start alert scheduling aborted as it is already running.");
   } else {
     _logger.info("Starting alert scheduling thread.");
     _alertSchedulingThread = new SchedulingThread("schedule-alerts", LockType.ALERT_SCHEDULING);
     _alertSchedulingThread.start();
     _logger.info("Alert scheduling thread started.");
   }
 }
예제 #2
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();
  }
예제 #3
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 stop() throws Exception {
    scheduleAllJobsOnApplicationStop();

    // this is enough to put the job into the queue, otherwise the jobs wont be executed
    // anyone got a better solution?
    Thread.sleep(100);

    scheduler.shutdown(true);
  }
예제 #5
0
 @Override
 public synchronized void stopAlertScheduling() {
   requireNotDisposed();
   if (_alertSchedulingThread != null && _alertSchedulingThread.isAlive()) {
     _logger.info("Stopping alert scheduling");
     _alertSchedulingThread.interrupt();
     _logger.info("Alert scheduling thread interrupted.");
     try {
       _logger.info("Waiting for alert scheduling thread to terminate.");
       _alertSchedulingThread.join();
     } catch (InterruptedException ex) {
       _logger.warn("Alert job scheduler was interrupted while shutting down.");
     }
     _logger.info("Alert job scheduling stopped.");
   } else {
     _logger.info("Requested shutdown of alert scheduling aborted as it is not yet running.");
   }
 }
예제 #6
0
  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();
  }
예제 #7
0
  public void run() throws Exception {
    Logger log = LoggerFactory.getLogger(JobStateExample.class);

    log.info("------- Initializing -------------------");

    // First we must get a reference to a scheduler
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    log.info("------- Initialization Complete --------");

    log.info("------- Scheduling Jobs ----------------");

    // get a "nice round" time a few seconds in the future....
    Date startTime = nextGivenSecondDate(null, 10);

    // job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds
    JobDetail job1 = newJob(ColorJob.class).withIdentity("job1", "group1").build();

    SimpleTrigger trigger1 =
        newTrigger()
            .withIdentity("trigger1", "group1")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4))
            .build();

    // pass initialization parameters into the job
    job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");
    job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);

    // schedule the job to run
    Date scheduleTime1 = sched.scheduleJob(job1, trigger1);
    log.info(
        job1.getKey()
            + " will run at: "
            + scheduleTime1
            + " and repeat: "
            + trigger1.getRepeatCount()
            + " times, every "
            + trigger1.getRepeatInterval() / 1000
            + " seconds");

    // job2 will also run 5 times, every 10 seconds
    JobDetail job2 = newJob(ColorJob.class).withIdentity("job2", "group1").build();

    SimpleTrigger trigger2 =
        newTrigger()
            .withIdentity("trigger2", "group1")
            .startAt(startTime)
            .withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4))
            .build();

    // pass initialization parameters into the job
    // this job has a different favorite color!
    job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Red");
    job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);

    // schedule the job to run
    Date scheduleTime2 = sched.scheduleJob(job2, trigger2);
    log.info(
        job2.getKey().toString()
            + " will run at: "
            + scheduleTime2
            + " and repeat: "
            + trigger2.getRepeatCount()
            + " times, every "
            + trigger2.getRepeatInterval() / 1000
            + " seconds");

    log.info("------- Starting Scheduler ----------------");

    // All of the jobs have been added to the scheduler, but none of the jobs
    // will run until the scheduler has been started
    sched.start();

    log.info("------- Started Scheduler -----------------");

    log.info("------- Waiting 60 seconds... -------------");
    try {
      // wait five minutes to show jobs
      Thread.sleep(60L * 1000L);
      // executing...
    } catch (Exception e) {
      //
    }

    log.info("------- Shutting Down ---------------------");

    sched.shutdown(true);

    log.info("------- Shutdown Complete -----------------");

    SchedulerMetaData metaData = sched.getMetaData();
    log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
  }
예제 #8
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;
    }