Quartz+SpringBoot实现动态管理定时任务
项目实践过程中碰到一个动态管理定时任务的需求:针对每个人员进行信息的定时更新,具体更新时间可随时调整、启动、暂定等。
创新互联专注于宁波网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供宁波营销型网站建设,宁波网站制作、宁波网页设计、宁波网站官网定制、小程序设计服务,打造宁波网络公司原创品牌,更为您提供宁波网站排名全网营销落地服务。
思路
将每个人员信息的定时配置保存到数据库中,这样实现了任务的动态展示和管理。任务的每一次新增或变更,都会去数据库变更信息。
设置一个统一的任务管理器,专门负责动态任务的增删改查。
POM依赖
<?xml version="1.0" encoding="UTF-8"?>application.yml spring: datasource: url: jdbc:mysql://localhost:3306/wujiwen username: root password: root driver-class-name: com.mysql.jdbc.Driver profiles: active: dev logback-spring.xml 4.0.0 com.example dynamic-quartz 0.0.1-SNAPSHOT jar dynamic-quartz 动态定时任务管理 org.springframework.boot spring-boot-starter-parent 2.0.2.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter org.springframework spring-context-support org.springframework.boot spring-boot-starter-test test org.mybatis.spring.boot mybatis-spring-boot-starter 1.1.1 MySQL mysql-connector-java 5.1.44 org.quartz-scheduler quartz 2.3.0 org.springframework.boot spring-boot-maven-plugin CronEntity.java 保存在数据库中的表达式管理器. package com.example.dynamicquartz.bean; import java.io.Serializable; import java.util.Date; /** * created with IntelliJ IDEA. * packageName : com.example.dynamicquartz.bean * author : wujw * date : 2018/9/9 16:23 * version : 1.0.0 * description : TODO */ public class CronEntity implements Serializable { private static final long serialVersionUID = -3406421161273529348L; private String id; private String userId; //用户标识 private String cron; //表达式 private String quarzName; //任务名称 private String schedulerClass;//定时任务类 private Date time; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getCron() { return cron; } public void setCron(String cron) { this.cron = cron; } public String getQuarzName() { return quarzName; } public void setQuarzName(String quarzName) { this.quarzName = quarzName; } public String getSchedulerClass() { return schedulerClass; } public void setSchedulerClass(String schedulerClass) { this.schedulerClass = schedulerClass; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } @Override public String toString() { return "CronEntity{" + "id='" + id + '\'' + ", userId='" + userId + '\'' + ", cron='" + cron + '\'' + ", quarzName='" + quarzName + '\'' + ", schedulerClass='" + schedulerClass + '\'' + ", time=" + time + '}'; } } CronMapper package com.example.dynamicquartz.dao; import com.example.dynamicquartz.bean.CronEntity; import org.apache.ibatis.annotations.*; import java.util.List; /** * created with IntelliJ IDEA. * packageName : com.example.dynamicquartz * author : wujw * date : 2018/9/9 20:14 * version : 1.0.0 * description : TODO */ @Mapper public interface CronMapper{ @Select("select * from cron_table where id = #{id}") @Results({ @Result(property = "id", column = "id"), @Result(property = "userId", column = "user_id"), @Result(property = "cron", column = "cron"), @Result(property = "quarzName", column = "quarz_name"), @Result(property = "schedulerClass", column = "scheduler_class"), @Result(property = "time", column = "time") }) CronEntity load(String id); @Insert("insert into cron_table(id,userId,cron,quartzName,schedulerClass,time)" + "values(#{id},#{user_id},#{cron},#{quartz_name},#{scheduler_class},# {time})") void insert(CronEntity cronEntity); @Select("select * from cron_table") @Results({ @Result(property = "id", column = "id"), @Result(property = "userId", column = "user_id"), @Result(property = "cron", column = "cron"), @Result(property = "quarzName", column = "quarz_name"), @Result(property = "schedulerClass", column = "scheduler_class"), @Result(property = "time", column = "time") }) List %date [%thread] %-5level %logger{80} - %msg%n queryAll(); @Update("update cron_table set cron=#{1} where id =#{0}") void updateCron(String id,String cron); } ICronService package com.example.dynamicquartz.serivce; import com.example.dynamicquartz.bean.CronEntity; import java.util.List; /** * created with IntelliJ IDEA. * packageName : com.example.dynamicquartz * author : wujw * date : 2018/9/9 19:54 * version : 1.0.0 * description : TODO */ public interface ICronService{ void sendEmail(String quartzName); void sendSms(String quartzName); CronEntity findByCronId(String id ); void update(CronEntity cronEntity); List findAll(); } CronServiceImpl package com.example.dynamicquartz.serivce; import com.example.dynamicquartz.bean.CronEntity; import com.example.dynamicquartz.dao.CronMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * created with IntelliJ IDEA. * packageName : com.example.dynamicquartz.serivce * author : wujw * date : 2018/9/9 19:55 * version : 1.0.0 * description : TODO */ @Service public class CronServiceImpl implements ICronService{ @Autowired private CronMapper cronMapper; @Override public void sendEmail(String quartzName) { System.out.println(quartzName +" 正在发送邮件"); } @Override public void sendSms(String quartzName) { System.out.println(quartzName +"正在发送短信"); } @Override public CronEntity findByCronId(String id) { return this.cronMapper.load(id); } @Override public void update(CronEntity cronEntity) { this.cronMapper.insert(cronEntity); } @Override public List findAll() { return this.cronMapper.queryAll(); } } QuartzManager package com.example.dynamicquartz.serivce; import com.example.dynamicquartz.bean.CronEntity; import org.quartz.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import java.util.Date; /** * created with IntelliJ IDEA. * packageName : com.example.dynamicquartz * author : wujw * date : 2018/9/9 19:31 * version : 1.0.0 * description : TODO */ @Configuration public class QuartzManager { @Autowired private Scheduler scheduler; @Autowired private ICronService iCronService; public void start(String id) throws SchedulerException { CronEntity cronEntity = iCronService.findByCronId(id); if(cronEntity!= null){ startJob(scheduler,cronEntity.getQuarzName(),cronEntity.getCron(),cronEntity.getSchedulerClass()); } } private void startJob(Scheduler scheduler,String name,String cron,String className) throws SchedulerException { // 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例 // JobDetail 是具体Job实例 Class jobClass = null; try { //实例化具体的Job任务 jobClass = (Class ) Class.forName(className); } catch (ClassNotFoundException e) { e.printStackTrace(); } JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(name, "group1").build(); // 基于表达式构建触发器 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron); // CronTrigger表达式触发器 继承于Trigger // TriggerBuilder 用于构建触发器实例 CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(name, "group1") .withSchedule(cronScheduleBuilder).build(); scheduler.scheduleJob(jobDetail, cronTrigger); } /** * 获取Job信息 * * @param name * @param group * @return * @throws SchedulerException */ public String getJobInfo(String name, String group) throws SchedulerException { TriggerKey triggerKey = new TriggerKey(name, group); CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey); return String.format("time:%s,state:%s", cronTrigger.getCronExpression(), scheduler.getTriggerState(triggerKey).name()); } /** * 修改某个任务的执行时间 * * @param name * @param group * @param time * @return * @throws SchedulerException */ public boolean modifyJob(String name, String group, String time) throws SchedulerException { Date date = null; TriggerKey triggerKey = new TriggerKey(name, group); CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey); String oldTime = cronTrigger.getCronExpression(); if (!oldTime.equalsIgnoreCase(time)) { CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time); CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group) .withSchedule(cronScheduleBuilder).build(); date = scheduler.rescheduleJob(triggerKey, trigger); } return date != null; } /** * 暂停所有任务 * * @throws SchedulerException */ public void pauseAllJob() throws SchedulerException { scheduler.pauseAll(); } /** * 暂停某个任务 * * @param name * @param group * @throws SchedulerException */ public void pauseJob(String name, String group) throws SchedulerException { JobKey jobKey = new JobKey(name, group); JobDetail jobDetail = scheduler.getJobDetail(jobKey); if (jobDetail == null) return; scheduler.pauseJob(jobKey); } /** * 恢复所有任务 * * @throws SchedulerException */ public void resumeAllJob() throws SchedulerException { scheduler.resumeAll(); } /** * 恢复某个任务 * * @param name * @param group * @throws SchedulerException */ public void resumeJob(String name, String group) throws SchedulerException { JobKey jobKey = new JobKey(name, group); JobDetail jobDetail = scheduler.getJobDetail(jobKey); if (jobDetail == null) return; scheduler.resumeJob(jobKey); } /** * 删除某个任务 * * @param name * @param group * @throws SchedulerException */ public void deleteJob(String name, String group) throws SchedulerException { JobKey jobKey = new JobKey(name, group); JobDetail jobDetail = scheduler.getJobDetail(jobKey); if (jobDetail == null) return; scheduler.deleteJob(jobKey); } } 创建两个Task类,分别执行不同的任务 public class EmailTask implements Job { private Logger logger = LoggerFactory.getLogger(EmailTask.class); @Autowired private ICronService iCronService; @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { logger.info("EmailTask task start execute."); //模拟任务执行 iCronService.sendEmail(jobExecutionContext.getJobDetail().getKey().getName()); } } public class SmsTask implements Job { private Logger logger = LoggerFactory.getLogger(SmsTask.class); @Autowired private ICronService iCronService; @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { logger.info("SmsTask task start execute."); //模拟任务执行 iCronService.sendSms(jobExecutionContext.getJobDetail().getKey().getName()); } } SchedulerController @RestController @RequestMapping("/scheduler") public class SchedulerController{ @Autowired QuartzManager quartzManager; @RequestMapping(value = "/start", method = RequestMethod.GET) @ResponseBody public String start(@RequestParam(name = "id", defaultValue = "") String id) { try { quartzManager.start(id); } catch (SchedulerException e) { e.printStackTrace(); } return "启动成功"; } } cron_table.sql CREATE TABLE `cron_table` ( `id` varchar(11) collate utf8_bin NOT NULL, `user_id` varchar(11) collate utf8_bin default NULL, `cron` varchar(255) collate utf8_bin default NULL, `quarz_name` varchar(255) collate utf8_bin default NULL, `scheduler_class` varchar(255) collate utf8_bin default NULL, `time` datetime default NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Records of cron_table -- ---------------------------- INSERT INTO `cron_table` VALUES ('1', 'AAA', '0/5 * * * * ?', '用户AAA', 'com.example.dynamicquartz.job.SmsTask', '2018-09-06 20:26:55'); INSERT INTO `cron_table` VALUES ('2', 'BBB', '0/2 * * * * ?', '用户BBB', 'com.example.dynamicquartz.job.EmailTask', '2018-09-09 21:02:08'); 测试结果 http://localhost:8080/scheduler/start?id=1 http://localhost:8080/scheduler/start?id=2 2018-09-09 21:05:08,386 [http-nio-8080-exec-2] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==> Preparing: select * from cron_table where id = ? 2018-09-09 21:05:08,408 [http-nio-8080-exec-2] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==> Parameters: 1(String) 2018-09-09 21:05:08,427 [http-nio-8080-exec-2] DEBUG com.example.dynamicquartz.dao.CronMapper.load - <== Total: 1 2018-09-09 21:05:10,036 [quartzScheduler_Worker-1] INFO com.example.dynamicquartz.job.SmsTask - SmsTask task start execute. 用户AAA正在发送短信 2018-09-09 21:05:11,581 [http-nio-8080-exec-1] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==> Preparing: select * from cron_table where id = ? 2018-09-09 21:05:11,582 [http-nio-8080-exec-1] DEBUG com.example.dynamicquartz.dao.CronMapper.load - ==> Parameters: 2(String) 2018-09-09 21:05:11,584 [http-nio-8080-exec-1] DEBUG com.example.dynamicquartz.dao.CronMapper.load - <== Total: 1 2018-09-09 21:05:12,013 [quartzScheduler_Worker-2] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute. 用户BBB 正在发送邮件 2018-09-09 21:05:14,002 [quartzScheduler_Worker-3] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute. 用户BBB 正在发送邮件 2018-09-09 21:05:15,001 [quartzScheduler_Worker-4] INFO com.example.dynamicquartz.job.SmsTask - SmsTask task start execute. 用户AAA正在发送短信 2018-09-09 21:05:16,001 [quartzScheduler_Worker-5] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute. 用户BBB 正在发送邮件 2018-09-09 21:05:18,001 [quartzScheduler_Worker-6] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute. 用户BBB 正在发送邮件 2018-09-09 21:05:20,000 [quartzScheduler_Worker-7] INFO com.example.dynamicquartz.job.SmsTask - SmsTask task start execute. 用户AAA正在发送短信 2018-09-09 21:05:20,001 [quartzScheduler_Worker-8] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute. 用户BBB 正在发送邮件 2018-09-09 21:05:22,001 [quartzScheduler_Worker-9] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute. 用户BBB 正在发送邮件 2018-09-09 21:05:24,000 [quartzScheduler_Worker-10] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute. 用户BBB 正在发送邮件 2018-09-09 21:05:25,001 [quartzScheduler_Worker-1] INFO com.example.dynamicquartz.job.SmsTask - SmsTask task start execute. 用户AAA正在发送短信 2018-09-09 21:05:26,000 [quartzScheduler_Worker-2] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute. 用户BBB 正在发送邮件 2018-09-09 21:05:28,001 [quartzScheduler_Worker-3] INFO com.example.dynamicquartz.job.EmailTask - EmailTask task start execute.
可以看出,AAA的间隔时间时5s,BBB的间隔时间时2s.
到这里我们的测试已经一本完成了,接下来就是针对任务的更新,停止和启动了,只需要调用 QuartzManager 对应的方法即可,必要时更新一下数据库就好啦。
总结
以上所述是小编给大家介绍的Quartz+Spring Boot实现动态管理定时任务,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对创新互联网站的支持!
网页标题:Quartz+SpringBoot实现动态管理定时任务
链接地址:http://scyanting.com/article/pihjjh.html