目标
- 基于目前系统quartz使用xml配置很繁琐,适配到spring boot
- 提供简单的接口,去动态触发任务
- 提供任务运行监控等
- 适用于基于数据库集群的分布式quartz
- 对于其他的需求可以参考 分布式任务系统 开源有好几个
结构
image.png
使用方式
- 引入quartz配置quartz.properties,或者使用默认的数据库集群
- application.properties 配置
# 集群名称
quartz.cluster.scheduler.name=xxx-DEV
# 启用
quartz.auto.start.up=true
- 代码中 集成AbstractQuartzJob,可以直接Autowired注入spring对象
@QuartzJob(cron = "0 0/30 * * * ?", desc = "测试任务")
public class XxxxJob extends AbstractQuartzJob {
@Autowired
private XxxxService XxxxService;
@Override
public void execute0(JobExecutionContext context) {
XxxxService.do();
}
- 获取spring注入的所有job实例,生成所有对应的JobDetail等
@Bean
public SchedulerFactoryBean schedulerFactoryBean(
@Qualifier("quartzDataSource") DataSource quartzDataSource, QuartzJobAndTriggerListener quartzJobAndTriggerListener) {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setApplicationContext(applicationContext);
schedulerFactoryBean.setStartupDelay(10);
schedulerFactoryBean.setOverwriteExistingJobs(true);
schedulerFactoryBean.setDataSource(quartzDataSource);
schedulerFactoryBean
.setConfigLocation(applicationContext.getResource("classpath:quartz.properties"));
schedulerFactoryBean.setGlobalJobListeners(quartzJobAndTriggerListener);
schedulerFactoryBean.setGlobalTriggerListeners(quartzJobAndTriggerListener);
schedulerFactoryBean.setJobFactory(jobFactory());
schedulerFactoryBean.setBeanName(schedulerClusterName);
Holder holder = getQuartzHolder();
schedulerFactoryBean.setAutoStartup(autoStartUp);
schedulerFactoryBean
.setJobDetails(holder.jobDetailList.toArray(new JobDetail[holder.jobDetailList.size()]));
schedulerFactoryBean
.setTriggers(holder.cronTriggerList.toArray(new Trigger[holder.cronTriggerList.size()]));
return schedulerFactoryBean;
}
public Holder getQuartzHolder() {
Map<String, Job> quartzJobMap = applicationContext.getBeansOfType(Job.class);
Set<String> quartNameSet = quartzJobMap.keySet();
List<CronTrigger> triggerList = Lists.newArrayList();
List<JobDetail> jobDetailList = Lists.newArrayList();
for (String quartName : quartNameSet) {
Job job = quartzJobMap.get(quartName);
QuartzJob quartzJob = AnnotationUtils.findAnnotation(job.getClass(), QuartzJob.class);
JobInfo jobInfo = JobInfo.create(quartzJob, job);
JobDetail jobDetail = JobBuilder.newJob(job.getClass()).withDescription(jobInfo.getDesc())
.storeDurably(true).withIdentity(jobInfo.getName(), jobInfo.getGroup()).build();
CronTrigger cronTrigger = TriggerBuilder.newTrigger().forJob(jobDetail)
.withIdentity(jobInfo.getName(), jobInfo.getGroup())
.withSchedule(CronScheduleBuilder.cronSchedule(jobInfo.getCron())).build();
jobDetailList.add(jobDetail);
triggerList.add(cronTrigger);
}
return new Holder(triggerList, jobDetailList);
}
网友评论