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);

本文介绍了如何在Spring Boot中集成Quartz进行动态任务管理,包括新建、更新、删除、暂停和恢复任务的操作。同时,文章讨论了在实际开发中遇到的初始化调度器、Bean注入、保存执行记录、监听器中注入业务Bean以及Job并发等问题,并提供了相应的解决方案。
最低0.47元/天 解锁文章
4万+

被折叠的 条评论
为什么被折叠?



