设计理念
执行的任务和时间规则分离,实现灵活组合1
Job2
释义:执行的任务
示例:
public class HelloJob implements Job {
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("Hello World!");
}
}
JobDetail
释义:Job定义,包含Job、Job的名称等信息3
示例:
//传入Class类的原因是,每次执行定时任务scheduler会通过反射创建一个新的HelloJob对象
JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("job1","group1").build();
JobDataMap
释义:用于同一个JobDetail下,多次执行定时任务之间实现数据共享
示例:
- 放数据
//usingJobData即是给JobDataMap里放数据
jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(jobClassName)).withIdentity(name, group).usingJobData(JobDataMapKey.MY_JD_ID,jobId).build();
- 取数据
@DisallowConcurrentExecution
public class SayHiTask extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDataMap dataMap = jobExecutionContext.getMergedJobDataMap();
Long jobId = dataMap.getLongValue(JobDataMapKey.MY_JD_ID)
System.out.println("say 'Hi!':"+jobId);
}
}
Trigger
释义:触发器,可简单认为是时间规则和JobDetail的组合
示例:
//时间规则
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/30 * * * * ?");
//触发器
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1","group1").startNow().withSchedule(scheduleBuilder).build();
Scheduler
释义:调度器。调度即取选并执行,选出此刻应该触发的Triggers,并执行其对应的任务
示例:
//调度:把任务和时间规则绑定起来
scheduler.scheduleJob(job,trigger);