Quartz提供了一组丰富的API,来管理Job。
前言
当定时任务越来越多时,集中管理Job越有必要。Quartz提供了一组丰富的API,来管理Job。
Spring Boot 定时任务之Quartz中讲了Spring Boot怎么集成quartz,这里结合实际业务,参考网上一些经验,总结一下集成的一些坑。
动态任务管理
下面以官方的例子来说明一下这些常用的API。
定义Job实现类
public class ColorJob implements Job {
public ColorJob() {
// Instances of Job must have a public no-argument constructor.
}
public void execute(JobExecutionContext context)
throws JobExecutionException {
JobDataMap data = context.getMergedJobDataMap();
System.out.println("someProp = " + data.getString("someProp"));
}
}
定义JobDetail
和Trigger
。
// Define job instance
JobDetail job1 = newJob(ColorJob.class)
.withIdentity("job1", "group1")
.build();
// Define a Trigger that will fire "now", and not repeat
Trigger trigger1 = newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.build();
新建
把Job添加到调度器sched中。
// Add the the job to the scheduler's store
sched.add(job1, trigger1);
更新
TriggerKey triggerKey = TriggerKey.triggerKey("job1", "group1");
// store, and set overwrite flag to 'true'
scheduler.addJob(job1, true);
// tell the scheduler to remove the old trigger with the given key, and put the new one in its place
scheduler.rescheduleJob(triggerKey, trigger1);
删除
JobKey jobKey = JobKey.jobKey("job1", "group1");
scheduler.deleteJob(jobKey);
暂停
JobKey jobKey = JobKey.jobKey("job1", "group1");
scheduler.pauseJob(jobKey);
恢复
JobKey jobKey = JobKey.jobKey("job1", "group1");
scheduler.resumeJob(jobKey);