org.quartz.Scheduler类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(15.9k)|赞(0)|评价(0)|浏览(168)

本文整理了Java中org.quartz.Scheduler类的一些代码示例,展示了Scheduler类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Scheduler类的具体详情如下:
包路径:org.quartz.Scheduler
类名称:Scheduler

Scheduler介绍

[英]This is the main interface of a Quartz Scheduler.

A Scheduler maintains a registry of org.quartz.JobDetails and Triggers. Once registered, the Scheduler is responsible for executing Job s when their associated Trigger s fire (when their scheduled time arrives).

Scheduler instances are produced by a SchedulerFactory. A scheduler that has already been created/initialized can be found and used through the same factory that produced it. After a Scheduler has been created, it is in "stand-by" mode, and must have its start() method called before it will fire any Jobs.

Job s are to be created by the 'client program', by defining a class that implements the org.quartz.Job interface. JobDetail objects are then created (also by the client) to define a individual instances of the Job. JobDetail instances can then be registered with the Scheduler via the scheduleJob(JobDetail, Trigger) or addJob(JobDetail, boolean) method.

Trigger s can then be defined to fire individual Job instances based on given schedules. SimpleTrigger s are most useful for one-time firings, or firing at an exact moment in time, with N repeats with a given delay between them. CronTrigger s allow scheduling based on time of day, day of week, day of month, and month of year.

Job s and Trigger s have a name and group associated with them, which should uniquely identify them within a single Scheduler. The 'group' feature may be useful for creating logical groupings or categorizations of Jobs s and Triggerss. If you don't have need for assigning a group to a given Jobs of Triggers, then you can use the DEFAULT_GROUP constant defined on this interface.

Stored Job s can also be 'manually' triggered through the use of the triggerJob(String jobName, String jobGroup) function.

Client programs may also be interested in the 'listener' interfaces that are available from Quartz. The JobListener interface provides notifications of Job executions. The TriggerListener interface provides notifications of Trigger firings. The SchedulerListener interface provides notifications of Scheduler events and errors. Listeners can be associated with local schedulers through the ListenerManager interface.

The setup/configuration of a Scheduler instance is very customizable. Please consult the documentation distributed with Quartz.
[中]

代码示例

代码示例来源:origin: xuxueli/xxl-job

JobKey jobKey = new JobKey(jobName, jobGroup);
if (scheduler.checkExists(triggerKey)) {
  return true;    // PASS
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();
JobDetail jobDetail = JobBuilder.newJob(jobClass_).withIdentity(jobKey).build();
Date date = scheduler.scheduleJob(jobDetail, cronTrigger);

代码示例来源:origin: apache/shiro

sessionValidationInterval);
JobDetail detail = new JobDetail(JOB_NAME, Scheduler.DEFAULT_GROUP, QuartzSessionValidationJob.class);
detail.getJobDataMap().put(QuartzSessionValidationJob.SESSION_MANAGER_KEY, sessionManager);
scheduler.scheduleJob(detail, trigger);
if (schedulerImplicitlyCreated) {
  scheduler.start();
  if (log.isDebugEnabled()) {
    log.debug("Successfully started implicitly created Quartz Scheduler instance.");

代码示例来源:origin: quartz-scheduler/quartz

@Override
public void stopService() throws Exception {
  log.info("Stop QuartzService(" + jndiName + ")...");
  try {
    Scheduler scheduler = schedulerFactory.getScheduler();
    scheduler.shutdown();
  } catch (Exception e) {
    log.error("Failed to shutdown Scheduler", e);
    throw new SchedulerConfigException(
        "Failed to shutdown Scheduler - ", e);
  }
  unbind(jndiName);
  log.info("QuartzService(" + jndiName + ") stopped.");
}

代码示例来源:origin: gocd/gocd

private void unscheduleJob(String pipelineName) {
  try {
    JobKey jobKey = jobKey(pipelineName, PIPELINE_TRIGGGER_TIMER_GROUP);
    if (quartzScheduler.getJobDetail(jobKey) != null) {
      quartzScheduler.unscheduleJob(triggerKey(pipelineName, PIPELINE_TRIGGGER_TIMER_GROUP));
      quartzScheduler.deleteJob(jobKey);
    }
  } catch (SchedulerException e) {
    LOG.error("Could not unschedule quartz jobs", e);
  }
}

代码示例来源:origin: elasticjob/elastic-job-lite

/**
   * 关闭调度器.
   */
  public synchronized void shutdown() {
    try {
      if (!scheduler.isShutdown()) {
        scheduler.shutdown();
      }
    } catch (final SchedulerException ex) {
      throw new JobSystemException(ex);
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Add the given job to the Scheduler, if it doesn't already exist.
 * Overwrites the job in any case if "overwriteExistingJobs" is set.
 * @param jobDetail the job to add
 * @return {@code true} if the job was actually added,
 * {@code false} if it already existed before
 * @see #setOverwriteExistingJobs
 */
private boolean addJobToScheduler(JobDetail jobDetail) throws SchedulerException {
  if (this.overwriteExistingJobs || getScheduler().getJobDetail(jobDetail.getKey()) == null) {
    getScheduler().addJob(jobDetail, true);
    return true;
  }
  else {
    return false;
  }
}

代码示例来源:origin: com.payneteasy.superfly/superfly-service

public static void rescheduleJob(JobExecutionContext context, Map<String, Object> dataMap) throws SchedulerException {
    String name = new RandomGUID().toString();
    JobDetail jobDetail = JobBuilder.newJob(context.getJobDetail().getJobClass())
        .withIdentity(name, GROUP)
        .usingJobData(new JobDataMap(dataMap))
        .build();
    Trigger trigger = TriggerBuilder.newTrigger()
        .withIdentity(name, GROUP)
        .startAt(new Date(new Date().getTime() + 1000 * 60))
        .build();
    context.getScheduler().scheduleJob(jobDetail, trigger);
  }
}

代码示例来源:origin: quartz-scheduler/quartz

dupeJ = sched.getJobDetail(detail.getKey());
} catch (JobPersistenceException e) {
  if (e.getCause() instanceof ClassNotFoundException && isOverWriteExistingData()) {
    log.info("Removing job: " + detail.getKey());
    sched.deleteJob(detail.getKey());
  } else {
    throw e;
    (sched.getTriggersOfJob(
      detail.getKey()).size() == 0))) {
    throw new SchedulerException(
    sched.addJob(detail, true, true);  // add the job regardless is durable or not b/c we have trigger to add
  else
    sched.addJob(detail, true, false); // add the job only if a replacement or durable, else exception will throw!
    Trigger dupeT = sched.getTrigger(trigger.getKey());
    if (dupeT != null) {
      if (isOverWriteExistingData()) {
      sched.rescheduleJob(trigger.getKey(), trigger);
    } else {
      if (log.isDebugEnabled()) {
          sched.scheduleJob(detail, trigger); // add the job if it's not in yet...
          addJobWithFirstSchedule = false;
        } else {
          sched.scheduleJob(trigger);

代码示例来源:origin: kiegroup/jbpm

dataMap.put("timerJobInstance", timerJobInstance);
JobDetail jobq = newJob(QuartzJob.class)
    .withIdentity(quartzJobHandle.getJobName(), quartzJobHandle.getJobGroup())
    .requestRecovery()
    .usingJobData(new JobDataMap(dataMap))
    .build();
Date threshold = new Date(System.currentTimeMillis() + RESCHEDULE_DELAY);
if (nextFireTime.before(threshold)) {
  logger.debug("nextFireTime [" + nextFireTime + "] is older than (now + RESCHEDULE_DELAY). Amending it to [" + threshold + "]");
  nextFireTime = threshold;
org.quartz.Trigger triggerq = newTrigger()
    .withIdentity(quartzJobHandle.getJobName()+"_trigger", quartzJobHandle.getJobGroup())
    .startAt(nextFireTime)                
    .build();
  if (scheduler.isShutdown()) {
    return;
  JobDetail jobDetail = scheduler.getJobDetail(jobKey(quartzJobHandle.getJobName(), quartzJobHandle.getJobGroup()));
  if (jobDetail == null) {
    scheduler.scheduleJob(jobq, triggerq);
  } else {
    scheduler.addJob(jobq, true, true);                
    scheduler.rescheduleJob(triggerq.getKey(), triggerq);

代码示例来源:origin: lamarios/Homedash2

/**
   * Create the scheduling jobs for refreshing the modules in the background
   */
  private static void prepareJobs() throws SchedulerException {
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler scheduler = sf.getScheduler();

    Date runTime = DateBuilder.evenMinuteDate(new Date());

    JobDetail job = JobBuilder.newJob(BackgroundRefresh.class).withIdentity("BackgroundRefresh", "HomeDash").build();

    Trigger trigger = TriggerBuilder.newTrigger().withIdentity("BackgroundRefresh", "HomeDash").withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
        .build();

    scheduler.scheduleJob(job, trigger);
    logger.info(job.getKey() + " will run at: " + runTime);

    scheduler.start();
  }
}

代码示例来源:origin: stackoverflow.com

SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();
scheduler.start();
JobDetail jobDetail = new JobDetail("someActionJob", Scheduler.DEFAULT_GROUP, ActionJob.class);

@SuppressWarnings("unchecked")
Map<String, Object> jobContext = jobDetail.getJobDataMap();
jobContext.put(QuartzActionConstants.NAMESPACE, "/the/action/namespace");
jobContext.put(QuartzActionConstants.NAME, "theActionName");
jobContext.put(QuartzActionConstants.METHOD, "theActionMethod");

Trigger trigger = new SimpleTrigger("actionJobTrigger", Scheduler.DEFAULT_GROUP, new Date(), null, SimpleTrigger.REPEAT_INDEFINITELY, 1000L);
scheduler.deleteJob("someActionJob", Scheduler.DEFAULT_GROUP);
scheduler.scheduleJob(jobDetail, trigger);

代码示例来源:origin: stackoverflow.com

public class DummyJob{

public DummyJob() throws ParseException, SchedulerException {

JobDetail job = new JobDetail();
job.setName("dummyJ");
job.setJobClass(NotificationCreater.class);

SimpleTrigger trigger = new SimpleTrigger();
trigger.setName("mn");
trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
trigger.setRepeatInterval(30000);

Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
 }
}

代码示例来源:origin: bonitasoft/bonita-engine

@Override
public void schedule(final long jobId, final String groupName, final String jobName, final Trigger trigger, final boolean disallowConcurrentExecution)
    throws SSchedulerException {
  try {
    checkSchedulerState();
    final JobDetail jobDetail = getJobDetail(jobId, groupName, jobName, disallowConcurrentExecution);
    final JobKey jobKey = jobDetail.getKey();
    final org.quartz.Trigger quartzTrigger = getQuartzTrigger(trigger, jobKey.getName(), jobKey.getGroup());
    scheduler.scheduleJob(jobDetail, quartzTrigger);
    if (useOptimization) {
      transactionService.registerBonitaSynchronization(new NotifyQuartzOfNewTrigger(trigger.getStartDate().getTime(), quartzScheduler));
    }
  } catch (final Exception e) {
    throw new SSchedulerException(e);
  }
}

代码示例来源:origin: net.sf.ehcache/ehcache

private void process(JobExecutionContext context, Ehcache underlyingCache, ScheduledRefreshConfiguration config,
          List<Serializable> batch) throws SchedulerException {
 JobDataMap map = new JobDataMap(context.getJobDetail().getJobDataMap());
 map.put(ScheduledRefreshCacheExtension.PROP_KEYS_TO_PROCESS, batch);
 Scheduler scheduler = context.getScheduler();
 JobDetail job = JobBuilder
   .newJob(RefreshBatchJob.class)
   .withIdentity("RefreshBatch-" + INSTANCE_ID_GENERATOR.incrementAndGet(),
     context.getTrigger().getJobKey().getGroup()).usingJobData(map).build();
 try {
   waitForOutstandingJobCount(context, config, scheduler, config.getParallelJobCount());
   if (!scheduler.isShutdown()) {
    Trigger trigger = TriggerBuilder.newTrigger().startNow().forJob(job).build();
    scheduler.scheduleJob(job, trigger);
   }
 } catch (SchedulerException e) {
   if (!scheduler.isShutdown()) {
    throw e;
   }
 }
}

代码示例来源:origin: sanluan/PublicCMS

TriggerKey triggerKey = TriggerKey.triggerKey(taskName);
try {
  CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
  CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
      .cronSchedule(site.getId() % 60 + CommonConstants.BLANK_SPACE + cronExpression);
  if (null == trigger) {
    JobDetail jobDetail = JobBuilder.newJob(ScheduledJob.class).withIdentity(taskName).build();
    jobDetail.getJobDataMap().put(ID, id);
    trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(scheduleBuilder).startNow()
        .build();
    scheduler.scheduleJob(jobDetail, trigger);
  } else {
    trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).startNow()
        .build();
    scheduler.rescheduleJob(triggerKey, trigger);
  logTaskService.save(new LogTask(site.getId(), id, startTime, CommonUtils.getDate(), false, e.getMessage()));

代码示例来源:origin: quartz-scheduler/quartz

getScheduler().getContext().put(JOB_INITIALIZATION_PLUGIN_NAME + '_' + getName(), this);
  getScheduler().unscheduleJob(tKey);
  JobDetail job = newJob().withIdentity(jobTriggerName, JOB_INITIALIZATION_PLUGIN_NAME).ofType(FileScanJob.class)
    .usingJobData(FileScanJob.FILE_NAME, jobFile.getFileName())
    .usingJobData(FileScanJob.FILE_SCAN_LISTENER_NAME, JOB_INITIALIZATION_PLUGIN_NAME + '_' + getName())
    .build();
  SimpleTrigger trig = newTrigger().withIdentity(tKey).withSchedule(
      simpleSchedule().repeatForever().withIntervalInMilliseconds(scanInterval))
      .forJob(job)
      .build();
  getScheduler().scheduleJob(job, trig);
  getLog().debug("Scheduled file scan job for data file: {}, at interval: {}", jobFile.getFileName(), scanInterval);

代码示例来源:origin: gocd/gocd

private void scheduleNewBackupJob(BackupConfig newBackupConfig) {
  if (newBackupConfig == null || isBlank(newBackupConfig.getSchedule())) {
    return;
  }
  try {
    JobDetail jobDetail = newJob()
        .withIdentity(jobKey())
        .ofType(ScheduleBackupQuartzJob.class)
        .usingJobData(jobDataMap())
        .build();
    CronTrigger trigger = newTrigger()
        .withIdentity(triggerKey())
        .withSchedule(cronSchedule(new CronExpression(newBackupConfig.getSchedule())))
        .build();
    quartzScheduler.scheduleJob(jobDetail, trigger);
    LOG.info("Initialized backup job with schedule " + newBackupConfig.getSchedule());
    clearServerHealthError();
  } catch (SchedulerException e) {
    LOG.error("Unable to schedule backup job", e);
    setServerHealthError("Unable to schedule backup job.", "Check the server log for detailed errors: " + e.getMessage());
  } catch (ParseException e) {
    LOG.error("Unable to schedule backup job", e);
    setServerHealthError("Unable to schedule backup job.", "Invalid cron syntax for backup configuration at offset " + e.getErrorOffset() + ": " + e.getMessage());
  }
}

代码示例来源:origin: wuyouzhuguli/FEBS-Shiro

/**
 * 创建定时任务
 */
public static void createScheduleJob(Scheduler scheduler, Job scheduleJob) {
  try {
    // 构建job信息
    JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getJobId()))
        .build();
    // 表达式调度构建器
    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
        .withMisfireHandlingInstructionDoNothing();
    // 按新的cronExpression表达式构建一个新的trigger
    CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getJobId()))
        .withSchedule(scheduleBuilder).build();
    // 放入参数,运行时的方法可以获取
    jobDetail.getJobDataMap().put(Job.JOB_PARAM_KEY, scheduleJob);
    scheduler.scheduleJob(jobDetail, trigger);
    // 暂停任务
    if (scheduleJob.getStatus().equals(Job.ScheduleStatus.PAUSE.getValue())) {
      pauseJob(scheduler, scheduleJob.getJobId());
    }
  } catch (SchedulerException e) {
    log.error("创建定时任务失败", e);
  }
}

代码示例来源:origin: apache/incubator-gobblin

/** {@inheritDoc} */
@Override protected JobSpecSchedule doScheduleJob(JobSpec jobSpec, Runnable jobRunnable) {
 // Build a data map that gets passed to the job
 JobDataMap jobDataMap = new JobDataMap();
 jobDataMap.put(JOB_SPEC_KEY, jobSpec);
 jobDataMap.put(JOB_RUNNABLE_KEY, jobRunnable);
 // Build a Quartz job
 JobDetail job = JobBuilder.newJob(QuartzJob.class)
   .withIdentity(jobSpec.getUri().toString())
   .withDescription(Strings.nullToEmpty(jobSpec.getDescription()))
   .usingJobData(jobDataMap)
   .build();
 Trigger jobTrigger = createTrigger(job.getKey(), jobSpec);
 QuartzJobSchedule jobSchedule = new QuartzJobSchedule(jobSpec, jobRunnable, jobTrigger);
 try {
  _scheduler.getScheduler().scheduleJob(job, jobTrigger);
  getLog().info(String.format("Scheduled job %s next two fire times: %s , %s.", jobSpec, jobTrigger.getNextFireTime(),
    jobTrigger.getFireTimeAfter(jobTrigger.getNextFireTime())));
 } catch (SchedulerException e) {
  throw new RuntimeException("Scheduling failed for " + jobSpec + ":" + e, e);
 }
 return jobSchedule;
}

代码示例来源:origin: azkaban/azkaban

throw new SchedulerException(String.format("can not register existing job with job name: "
   + "%s and group name: %s", jobDescription.getJobName(), jobDescription.getGroupName()));
 throw new SchedulerException(
   "The cron expression string <" + cronExpression + "> is not valid.");
final JobDetail job = JobBuilder.newJob(jobDescription.getJobClass())
  .withIdentity(jobDescription.getJobName(), jobDescription.getGroupName()).build();
job.getJobDataMap().putAll(jobDescription.getContextMap());
  .newTrigger()
  .withSchedule(
    CronScheduleBuilder.cronSchedule(cronExpression)
      .withMisfireHandlingInstructionFireAndProceed()
  .build();
this.scheduler.scheduleJob(job, trigger);
logger.info("Quartz Schedule with jobDetail " + job.getDescription() + " is registered.");

相关文章