前言
用到过Quartz定时任务框架的,第一眼看到Quartz就肯定会想起,调度工厂JobFactory、触发器 Trigger、任务实例Job。
那么该篇,就会结合实战案例来一步一步让大家都了解,怎么玩弄这个Quartz框架,能实现 所谓的动态调度 。
内容:
1.随项目启动即运行的 定时任务
2.动态触发的定时任务 ,包括:
随时创建新的定时任务;
随时执行指定的某个定时任务;
随时暂停指定的某个定时任务;
随时重启指定的某个定时任务;
随时删除指定的某个定时任务;
随时查看指定的某个定时任务;
3.动态传参到任务实例
4.可结合数据库扩展
正文
惯例,在开始实战案例前,先看一眼最终的项目目录结构:
接下来开始编码,
首先是pom.xml里的核心依赖包:
<!-- web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- quartz --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.3</version> </dependency> <!-- spring集成quartz --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <!--fastjson--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.58</version> </dependency>
接着现在编码一些关于配置相关的,
创建JobEntity.java(定时任务使用的动态参数 实体类):
import com.alibaba.fastjson.JSONObject; import java.util.Date; /** * @Author : JCccc * @CreateTime : 2020/3/21 * @Description : 定时任务用到的参数 **/ public class JobEntity { private String jobId; //唯一id private String className; //定时任务示例的 class路径 private String cronExpression; //cron表达式 private String jobName; //定时任务名称 private String jobGroup; //所属组 private String triggerName; //触发器名称 private String triggerGroup; //触发器组 private String description; //备注 private JSONObject data; //携带参数 /** * 预留的数据库字段 如果任务信息选择手动自己存入数据库的话,会使用到 */ private Boolean pauseStatus; //是否暂停 private Boolean deleteStatus; //是否有效 private Date createTime; //创建时间 private Date updateTime; //更新时间 @Override public String toString() { return "JobEntity{" + "jobId='" + jobId + '\'' + ", className='" + className + '\'' + ", cronExpression='" + cronExpression + '\'' + ", jobName='" + jobName + '\'' + ", jobGroup='" + jobGroup + '\'' + ", triggerName='" + triggerName + '\'' + ", triggerGroup='" + triggerGroup + '\'' + ", description='" + description + '\'' + ", data=" + data + ", pauseStatus=" + pauseStatus + ", deleteStatus=" + deleteStatus + ", createTime=" + createTime + ", updateTime=" + updateTime + '}'; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getJobGroup() { return jobGroup; } public void setJobGroup(String jobGroup) { this.jobGroup = jobGroup; } public String getTriggerName() { return triggerName; } public void setTriggerName(String triggerName) { this.triggerName = triggerName; } public String getTriggerGroup() { return triggerGroup; } public void setTriggerGroup(String triggerGroup) { this.triggerGroup = triggerGroup; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public JSONObject getData() { return data; } public void setData(JSONObject data) { this.data = data; } public Boolean getPauseStatus() { return pauseStatus; } public void setPauseStatus(Boolean pauseStatus) { this.pauseStatus = pauseStatus; } public Boolean getDeleteStatus() { return deleteStatus; } public void setDeleteStatus(Boolean deleteStatus) { this.deleteStatus = deleteStatus; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
创建JobFactory.java (job实例工厂):
import org.quartz.spi.TriggerFiredBundle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.scheduling.quartz.AdaptableJobFactory; import org.springframework.stereotype.Component; /** * @Author : JCccc * @CreateTime : 2020/3/21 * @Description : 创建job实例工厂,使用默认的也许会出现spring的@Autowired 无法注入问题 * **/ @Component public class JobFactory extends AdaptableJobFactory { @Autowired private AutowireCapableBeanFactory beanFactory; @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { Object jobInstance = super.createJobInstance(bundle); //Job实例注入到Job工厂 beanFactory.autowireBean(jobInstance); return jobInstance; } }
创建QuartzConfig.java (一些属性配置项):
import org.quartz.Scheduler; import org.quartz.ee.servlet.QuartzInitializerListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import java.io.IOException; import java.util.Properties; /** * @Author : JCccc * @CreateTime : 2020/3/21 * @Description : 调度工厂,线程池属性等等配置 **/ @Configuration public class QuartzConfig { @Autowired private JobFactory jobFactory; /** * 调度类FactoryBean * @return * @throws IOException */ @Bean("schedulerFactory") public SchedulerFactoryBean schedulerFactoryBean() throws IOException { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); //设置调度类quartz属性 schedulerFactoryBean.setQuartzProperties(quartzProperties()); //设置jobFactory schedulerFactoryBean.setJobFactory(jobFactory); return schedulerFactoryBean; } /** * 解析quartz.properties文件,填充属性 * @return * @throws IOException */ @Bean public Properties quartzProperties() throws IOException{ PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); //若不做额外配置,会有默认的配置文件加载 在jar org.quartz里面 有一份quartz.properties //propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); } /** * quartz初始化监听器 * @return */ @Bean public QuartzInitializerListener initializerListener(){ return new QuartzInitializerListener(); } /** * 根据调度类工厂bean获取调度 * @return * @throws IOException */ @Bean("scheduler") public Scheduler scheduler() throws IOException{ return schedulerFactoryBean().getScheduler(); } }
ps:这里的配置项,特别是关于quartz的配置项,可以自己去写配置文件配置,但是该篇就使用默认的就够,默认的是jar包自己提供的:
简单瞅一眼:
相关参数什么作用,不懂的对着英文查询翻译即可,该篇不做展开。
接着,咱们实现一个调度方法类,类似于我们使用别的框架的Template一样。
新建QuartzService.java:
import com.alibaba.fastjson.JSONObject; import com.bsapple.vshop.quartz.config.JobEntity; /** * @Author : JCccc * @CreateTime : 2020/3/21 * @Description : **/ public interface QuartzService { /** * 创建Job * @param job */ Boolean addJob(JobEntity job); /** * 执行Job * @param job */ Boolean runJob(JobEntity job); /** * 修改Job * @param job */ Boolean updateJob(JobEntity job); /** * 暂定Job * @param job */ Boolean pauseJob(JobEntity job); /** * 唤醒Job * @param job */ Boolean resumeJob(JobEntity job); /** * 删除Job * @param job */ Boolean deleteJob(JobEntity job); /** * 获取Job * @param job */ JSONObject queryJob(JobEntity job); }
对应的impl,QuartzServiceImpl.java:
import com.alibaba.fastjson.JSONObject; import com.bsapple.vshop.quartz.config.JobEntity; import org.quartz.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; /** * @Author : JCccc * @CreateTime : 2020/3/21 * @Description : **/ @Service public class QuartzServiceImpl implements QuartzService { private static Logger log = LoggerFactory.getLogger(QuartzServiceImpl.class); @Autowired @Qualifier("scheduler") private Scheduler scheduler; @Override public Boolean addJob(JobEntity job) { try { JSONObject data = job.getData(); log.info("当前任务携带的业务参数={}", data.toJSONString()); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put("myValue", data); String jobId = job.getJobId(); String jobName = job.getJobName(); String jobUnique = jobId + jobName; JobDetail jobDetail = JobBuilder .newJob((Class<? extends Job>) Class.forName(job.getClassName())) // 指定执行类 .withIdentity(jobUnique, job.getJobGroup()) // 指定name和group .requestRecovery().withDescription(job.getDescription()) .setJobData(jobDataMap) .build(); // 创建表达式调度构建器 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder .cronSchedule(job.getCronExpression()); // 创建触发器 CronTrigger cronTrigger = TriggerBuilder.newTrigger() .withIdentity(job.getTriggerName(), job.getTriggerGroup()) .withDescription(job.getDescription()) .withSchedule(cronScheduleBuilder).build(); scheduler.scheduleJob(jobDetail, cronTrigger); scheduler.start(); log.info("定时任务[{}]创建成功,开始执行", jobId + jobName); return true; } catch (Exception e) { e.printStackTrace(); } return false; } @Override public Boolean runJob(JobEntity job) { try { String jobId = job.getJobId(); String jobName = job.getJobName(); String jobUnique = jobId + jobName; scheduler.triggerJob(JobKey.jobKey(jobUnique, job.getJobGroup())); log.info("定时任务[{}]执行成功", jobUnique); return true; } catch (Exception e) { e.printStackTrace(); } return false; } @Override public Boolean updateJob(JobEntity job) { try { String jobId = job.getJobId(); String jobName = job.getJobName(); String jobUnique = jobId + jobName; TriggerKey triggerKey = new TriggerKey(job.getTriggerName(), job.getTriggerGroup()); CronTrigger cronTrigger = (CronTrigger) scheduler .getTrigger(triggerKey); CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder .cronSchedule(job.getCronExpression()); // 重新构件表达式 CronTrigger trigger = cronTrigger.getTriggerBuilder() .withIdentity(triggerKey).withSchedule(cronScheduleBuilder) .withDescription(job.getDescription()) .build(); scheduler.rescheduleJob(triggerKey, trigger); log.info("定时任务[{}]更新成功", jobUnique); return true; } catch (Exception e) { e.printStackTrace(); } return false; } @Override public Boolean pauseJob(JobEntity job) { try { String jobId = job.getJobId(); String jobName = job.getJobName(); String jobUnique = jobId + jobName; scheduler.pauseJob(JobKey.jobKey(jobUnique, job.getJobGroup())); log.info("定时任务[{}]暂停成功", jobUnique); return true; } catch (Exception e) { e.printStackTrace(); } return false; } @Override public Boolean resumeJob(JobEntity job) { try { String jobId = job.getJobId(); String jobName = job.getJobName(); String jobUnique = jobId + jobName; scheduler.resumeJob(JobKey.jobKey(jobUnique, job.getJobGroup())); log.info("定时任务[{}]唤醒成功", jobUnique); return true; } catch (Exception e) { e.printStackTrace(); } return false; } @Override public Boolean deleteJob(JobEntity job) { try { String jobId = job.getJobId(); String jobName = job.getJobName(); String jobUnique = jobId + jobName; scheduler.deleteJob(JobKey.jobKey(jobUnique, job.getJobGroup())); log.info("定时任务[{}]删除成功", jobUnique); return true; } catch (Exception e) { e.printStackTrace(); } return false; } @Override public JSONObject queryJob(JobEntity job) { TriggerKey triggerKey = new TriggerKey(job.getTriggerName(), job.getTriggerGroup()); try { CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey); if (null == cronTrigger) { return null; } JSONObject jsonObject = new JSONObject(); jsonObject.put("expression", cronTrigger.getCronExpression()); jsonObject.put("state", scheduler.getTriggerState(triggerKey)); jsonObject.put("description", cronTrigger.getDescription()); return jsonObject; } catch (Exception e) { e.printStackTrace(); } return null; } }
到这,其实动态的调度定时任务条件,我们都已经准备充分了。
接下来是使用环节:
1.随着项目启动就启动的定时任务
之所以能随着项目启动就跟着启动,那么显然,就跟监听项目启动有关系。
创建MyJobAuto.java ,继承job,做为定时任务示例:
/** * @Author : JCccc * @CreateTime : 2020/3/21 * @Description : **/ import com.alibaba.fastjson.JSONObject; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @Component public class MyJobAuto implements Job { private static Logger log = LoggerFactory.getLogger(MyJobAuto.class); private void before() { log.info("******MyJobAuto任务开始执行******"); } @Override public void execute(JobExecutionContext context) { before(); //定时任务处理的业务逻辑 //... //... String name = context.getJobDetail().getKey().getName(); log.info("******MyJobAuto任务[{}]正在执行******",name); JobDataMap jobDataMap=context.getJobDetail().getJobDataMap(); JSONObject jsonObject = (JSONObject) jobDataMap.get("myValue"); log.info("MyJobAuto任务[{}]携带的参数[{}]",name,jsonObject.toString()); String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); log.info("当前时间[{}],MyJobAuto任务[{}]的线程名[{}]",time,name,Thread.currentThread().getName()); after(); } private void after() { log.info("******MyJobAuto任务执行结束******"); } }
然后是项目启动监听器,创建ApplicationStartListener.java:
import com.alibaba.fastjson.JSONObject; import com.bsapple.vshop.quartz.config.JobEntity; import com.bsapple.vshop.quartz.jobManage.QuartzService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ContextRefreshedEvent; import java.util.UUID; /** * @Author : JCccc * @CreateTime : 2020/3/21 * @Description : **/ @Configuration public class ApplicationStartListener implements ApplicationListener<ContextRefreshedEvent> { private static Logger log = LoggerFactory.getLogger(ApplicationStartListener.class); @Autowired private QuartzService quartzService; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { JobEntity job=new JobEntity(); job.setJobId(UUID.randomUUID().toString().replaceAll("-","")); job.setClassName("com.bsapple.vshop.quartz.taskJob.MyJobAuto");//注意,这里的路径请改成你自己的 job.setCronExpression("0/3 * * * * ?"); job.setJobName("AutoJob"); job.setJobGroup("AutoJobGroup"); job.setTriggerName("AutoJobTrigger"); job.setTriggerGroup("AutoJobTriggerGroup"); job.setDescription("AutoJob-随项目启动"); //可以将任务跟数据库挂钩,做个任务管理模块,获取需要自启动的任务,记录各个参数等 JSONObject jsonObject=new JSONObject(); jsonObject.put("testKey","测试即启动"); job.setData(jsonObject); quartzService.addJob(job); log.info("即触发定时任务已经开始执行.. ."); log.info("************application已经启动完毕************"); } }
事不宜迟,先把项目启动起来看看效果,成功执行,根据cron表达式,3秒一次:
再看一眼线程名里面,可以看到quartz加载了默认配置,线程数量10:
2.动态调度定时任务
我们在前面已经把调度方法的模版已经写了,那么实现调度场景就非常简单了。
创建QuartzController.java:
import com.alibaba.fastjson.JSONObject; import com.bsapple.vshop.quartz.config.JobEntity; import com.bsapple.vshop.quartz.jobManage.QuartzService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * @Author : JCccc * @CreateTime : 2020/3/21 * @Description : **/ @RestController @RequestMapping("/quartz") public class QuartzController { @Autowired private QuartzService quartzService; @PostMapping("/add") public String addJob(@RequestBody JobEntity job) { Boolean result = quartzService.addJob(job); if (!result) { return "创建定时任务失败"; } return "创建定时任务成功:"+job.getJobId()+job.getJobName(); } @PostMapping("/run") public String runJob(@RequestBody JobEntity job) { Boolean result = quartzService.runJob(job); if (!result) { return "启动定时任务失败"; } return "启动定时任务成功:"+job.getJobId()+job.getJobName(); } @PostMapping("/update") public String updateJob(@RequestBody JobEntity job) { Boolean result = quartzService.updateJob(job); if (!result) { return "修改定时任务失败"; } return "修改定时任务成功:"+job.getJobId()+job.getJobName(); } @PostMapping("/pause") public String pauseJob(@RequestBody JobEntity job) { Boolean result = quartzService.pauseJob(job); if (!result) { return "暂停定时任务失败"; } return "暂停定时任务成功:"+job.getJobId()+job.getJobName(); } @PostMapping("/resume") public String resumeJob(@RequestBody JobEntity job) { Boolean result = quartzService.resumeJob(job); if (!result) { return "唤醒定时任务失败"; } return "唤醒定时任务成功:"+job.getJobId()+job.getJobName(); } @PostMapping("/delete") public String deleteJob(@RequestBody JobEntity job) { Boolean result = quartzService.deleteJob(job); if (!result) { return "删除定时任务失败"; } return "删除定时任务成功:"+job.getJobId()+job.getJobName(); } @GetMapping("/query") public String queryJob(@RequestBody JobEntity job) { JSONObject result = quartzService.queryJob(job); if (null == result) { return "不存在对应的任务:"+job.getJobId()+job.getJobName(); } return result.toString(); } }
简单写两个定时任务,模拟多定时任务调度处理不同业务:
MyJobFirst.java:
/** * @Author : JCccc * @CreateTime : 2020/3/21 * @Description : **/ import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import com.alibaba.fastjson.JSONObject; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class MyJobFirst implements Job { private static Logger log = LoggerFactory.getLogger(MyJobFirst.class); private void before() { log.info("******MyJobFirst任务开始执行******"); } @Override public void execute(JobExecutionContext context) { before(); //定时任务处理的业务逻辑 //... //... String name = context.getJobDetail().getKey().getName(); log.info("******MyJobFirst任务[{}]正在执行******",name); JobDataMap jobDataMap=context.getJobDetail().getJobDataMap(); JSONObject jsonObject = (JSONObject) jobDataMap.get("myValue"); log.info("MyJobFirst任务[{}]携带的参数[{}]",name,jsonObject.toString()); String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); log.info("当前时间[{}],MyJobFirst任务[{}]的线程名[{}]",time,name,Thread.currentThread().getName()); after(); } private void after() { log.info("******MyJobFirst任务执行结束******"); } }
MyJobSecond.java:
/** * @Author : JCccc * @CreateTime : 2020/3/21 * @Description : **/ import com.alibaba.fastjson.JSONObject; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; @Component public class MyJobSecond implements Job { private static Logger log = LoggerFactory.getLogger(MyJobSecond.class); private void before() { log.info("******MyJobSecond任务开始执行******"); } @Override public void execute(JobExecutionContext context) { before(); //定时任务处理的业务逻辑 //... //... String name = context.getJobDetail().getKey().getName(); log.info("******MyJobSecond任务[{}]正在执行******",name); JobDataMap jobDataMap=context.getJobDetail().getJobDataMap(); JSONObject jsonObject = (JSONObject) jobDataMap.get("myValue"); log.info("MyJobSecond任务[{}]携带的参数[{}]",name,jsonObject.toString()); String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); log.info("当前时间[{}],MyJobSecond任务[{}]的线程名[{}]",time,name,Thread.currentThread().getName()); after(); } private void after() { log.info("******MyJobSecond任务执行结束******"); } }
把项目重启一下,为了给大家展示这个动态调度效果,我自己先把监听启动的定时任务先注释了。
调用创建定时任务接口:
{ "jobId":"1111111JCccc1111", "className":"com.bsapple.vshop.quartz.taskJob.MyJobFirst", "cronExpression":"0/7 * * * * ?", "jobName":"testJobF", "jobGroup":"testGroupF", "triggerName":"trF", "triggerGroup":"trGroupF", "description":"test JcAAAA", "data":{"v1":"A","v2":"AAA","v3":"AAAA"} }
执行效果:
继续把任务二也创建一下启动起来:
{ "jobId":"22222JCccc22222", "className":"com.bsapple.vshop.quartz.taskJob.MyJobSecond", "cronExpression":"0/5 * * * * ?", "jobName":"testJobS", "jobGroup":"testGroupS", "triggerName":"trS", "triggerGroup":"trGroupS", "description":"test JcBBBBB", "data":{"v1":"B","v2":"B","v3":"B"} }
效果,可以看到两个定时任务都在执行:
暂停指定任务,调用/quartz/pause接口 :
ps:注意该篇是展示的通过接口去暂停,实际上很多业务场景是定时任务处理业务逻辑的代码端里面,根据某些值去判断去操作当前定时任务,选择停止还是删除,还是先停止到达某个值再唤醒等等,或者是符合某个条件去开启别的定时任务,这些都是根据业务场景可以自己扩展。
可以看到暂停方法里面需要使用到的相关参数是:
所以我们接口传参只需要:
{ "jobId":"1111111JCccc1111", "jobName":"testJobF", "jobGroup":"testGroupF" }
效果,可以看到第一个任务暂停成功后,剩下第二个任务在继续执行:
那么还有
唤醒指定定时任务接口 /quartz/resume
删除指定定时任务接口 /quartz/delete
更新指定定时任务接口 /quartz/update
查看指定定时任务状态接口 /quartz/query
都是一样的调用方法接口,就不一一做截图展示了。
最后,还是建议调度任务的实例数据存入数据库,这样跟数据库挂钩起来运用就灵活更多了。不管是结合mysql,oracle或者说redis,都可以有更多扩展,解决分布式调度等等。
不过该篇实战案例介绍也应该满足大多数使用场景了。
那么该篇就先到此。