Spring Boot 定时任务,怎么实现任务动态增删启停?
Posted Java技术栈
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot 定时任务,怎么实现任务动态增删启停?相关的知识,希望对你有一定的参考价值。
作者:jessehua
链接:https://www.jianshu.com/p/0f68936393fd
在spring boot项目中,可以通过@EnableScheduling注解和@Scheduled注解实现定时任务,也可以通过SchedulingConfigurer接口来实现定时任务。但是这两种方式不能动态添加、删除、启动、停止任务。要实现动态增删启停定时任务功能,比较广泛的做法是集成Quartz框架。
但是本人的开发原则是:在满足项目需求的情况下,尽量少的依赖其它框架,避免项目过于臃肿和复杂。查看spring-context这个jar包中org.springframework.scheduling.ScheduledTaskRegistrar这个类的源代码,发现可以通过改造这个类就能实现动态增删启停定时任务功能。
Spring Boot 基础就不介绍了,推荐下这个实战教程:
https://github.com/javastacks/spring-boot-best-practice
添加执行定时任务的线程池配置类
@Configuration
public class SchedulingConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
// 定时任务执行线程池核心线程数
taskScheduler.setPoolSize(4);
taskScheduler.setRemoveOnCancelPolicy(true);
taskScheduler.setThreadNamePrefix("TaskSchedulerThreadPool-");
return taskScheduler;
}
}
添加ScheduledFuture的包装类。ScheduledFuture是ScheduledExecutorService定时任务线程池的执行结果。
public final class ScheduledTask {
volatile ScheduledFuture<?> future;
/**
* 取消定时任务
*/
public void cancel() {
ScheduledFuture<?> future = this.future;
if (future != null) {
future.cancel(true);
}
}
}
添加Runnable接口实现类,被定时任务线程池调用,用来执行指定bean里面的方法。
public class SchedulingRunnable implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(SchedulingRunnable.class);
private String beanName;
private String methodName;
private String params;
public SchedulingRunnable(String beanName, String methodName) {
this(beanName, methodName, null);
}
public SchedulingRunnable(String beanName, String methodName, String params) {
this.beanName = beanName;
this.methodName = methodName;
this.params = params;
}
@Override
public void run() {
logger.info("定时任务开始执行 - bean:{},方法:{},参数:{}", beanName, methodName, params);
long startTime = System.currentTimeMillis();
try {
Object target = SpringContextUtils.getBean(beanName);
Method method = null;
if (StringUtils.isNotEmpty(params)) {
method = target.getClass().getDeclaredMethod(methodName, String.class);
} else {
method = target.getClass().getDeclaredMethod(methodName);
}
ReflectionUtils.makeAccessible(method);
if (StringUtils.isNotEmpty(params)) {
method.invoke(target, params);
} else {
method.invoke(target);
}
} catch (Exception ex) {
logger.error(String.format("定时任务执行异常 - bean:%s,方法:%s,参数:%s ", beanName, methodName, params), ex);
}
long times = System.currentTimeMillis() - startTime;
logger.info("定时任务执行结束 - bean:{},方法:{},参数:{},耗时:{} 毫秒", beanName, methodName, params, times);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SchedulingRunnable that = (SchedulingRunnable) o;
if (params == null) {
return beanName.equals(that.beanName) &&
methodName.equals(that.methodName) &&
that.params == null;
}
return beanName.equals(that.beanName) &&
methodName.equals(that.methodName) &&
params.equals(that.params);
}
@Override
public int hashCode() {
if (params == null) {
return Objects.hash(beanName, methodName);
}
return Objects.hash(beanName, methodName, params);
}
}
添加定时任务注册类,用来增加、删除定时任务。
@Component
public class CronTaskRegistrar implements DisposableBean {
private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);
@Autowired
private TaskScheduler taskScheduler;
public TaskScheduler getScheduler() {
return this.taskScheduler;
}
public void addCronTask(Runnable task, String cronExpression) {
addCronTask(new CronTask(task, cronExpression));
}
public void addCronTask(CronTask cronTask) {
if (cronTask != null) {
Runnable task = cronTask.getRunnable();
if (this.scheduledTasks.containsKey(task)) {
removeCronTask(task);
}
this.scheduledTasks.put(task, scheduleCronTask(cronTask));
}
}
public void removeCronTask(Runnable task) {
ScheduledTask scheduledTask = this.scheduledTasks.remove(task);
if (scheduledTask != null)
scheduledTask.cancel();
}
public ScheduledTask scheduleCronTask(CronTask cronTask) {
ScheduledTask scheduledTask = new ScheduledTask();
scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
return scheduledTask;
}
@Override
public void destroy() {
for (ScheduledTask task : this.scheduledTasks.values()) {
task.cancel();
}
this.scheduledTasks.clear();
}
}
添加定时任务示例类
@Component("demoTask")
public class DemoTask {
public void taskWithParams(String params) {
System.out.println("执行有参示例任务:" + params);
}
public void taskNoParams() {
System.out.println("执行无参示例任务");
}
}
定时任务数据库表设计
添加定时任务实体类
public class SysJobPO {
/**
* 任务ID
*/
private Integer jobId;
/**
* bean名称
*/
private String beanName;
/**
* 方法名称
*/
private String methodName;
/**
* 方法参数
*/
private String methodParams;
/**
* cron表达式
*/
private String cronExpression;
/**
* 状态(1正常 0暂停)
*/
private Integer jobStatus;
/**
* 备注
*/
private String remark;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
public Integer getJobId() {
return jobId;
}
public void setJobId(Integer jobId) {
this.jobId = jobId;
}
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getMethodParams() {
return methodParams;
}
public void setMethodParams(String methodParams) {
this.methodParams = methodParams;
}
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public Integer getJobStatus() {
return jobStatus;
}
public void setJobStatus(Integer jobStatus) {
this.jobStatus = jobStatus;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
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;
}
}
新增定时任务
新增定时任务
boolean success = sysJobRepository.addSysJob(sysJob);
if (!success)
return OperationResUtils.fail("新增失败");
else {
if (sysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression());
}
}
return OperationResUtils.success();
修改定时任务,先移除原来的任务,再启动新任务
boolean success = sysJobRepository.editSysJob(sysJob);
if (!success)
return OperationResUtils.fail("编辑失败");
else {
//先移除再添加
if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
cronTaskRegistrar.removeCronTask(task);
}
if (sysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression());
}
}
return OperationResUtils.success();
删除定时任务
boolean success = sysJobRepository.deleteSysJobById(req.getJobId());
if (!success)
return OperationResUtils.fail("删除失败");
else{
if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
cronTaskRegistrar.removeCronTask(task);
}
}
return OperationResUtils.success();
定时任务启动/停止状态切换
if (existedSysJob.getJobStatus().equals(SysJobStatus.NORMAL.ordinal())) {
SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
cronTaskRegistrar.addCronTask(task, existedSysJob.getCronExpression());
} else {
SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams());
cronTaskRegistrar.removeCronTask(task);
}
添加实现了CommandLineRunner接口的SysJobRunner类,当spring boot项目启动完成后,加载数据库里状态为正常的定时任务。
@Service
public class SysJobRunner implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(SysJobRunner.class);
@Autowired
private ISysJobRepository sysJobRepository;
@Autowired
private CronTaskRegistrar cronTaskRegistrar;
@Override
public void run(String... args) {
// 初始加载数据库里状态为正常的定时任务
List<SysJobPO> jobList = sysJobRepository.getSysJobListByStatus(SysJobStatus.NORMAL.ordinal());
if (CollectionUtils.isNotEmpty(jobList)) {
for (SysJobPO job : jobList) {
SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
cronTaskRegistrar.addCronTask(task, job.getCronExpression());
}
logger.info("定时任务已加载完毕...");
}
}
}
工具类SpringContextUtils,用来从spring容器里获取bean
@Component
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
public static <T> T getBean(String name, Class<T> requiredType) {
return applicationContext.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) {
return applicationContext.isSingleton(name);
}
public static Class<? extends Object> getType(String name) {
return applicationContext.getType(name);
}
}
近期热文推荐:
1.1,000+ 道 Java面试题及答案整理(2021最新版)
2.别在再满屏的 if/ else 了,试试策略模式,真香!!
3.卧槽!Java 中的 xx ≠ null 是什么新语法?
4.Spring Boot 2.5 重磅发布,黑暗模式太炸了!
觉得不错,别忘了随手点赞+转发哦!
Quartz+Spring Boot实现动态管理定时任务
项目实践过程中碰到一个动态管理定时任务的需求:针对每个人员进行信息的定时更新,具体更新时间可随时调整、启动、暂定等。
思路
将每个人员信息的定时配置保存到数据库中,这样实现了任务的动态展示和管理。任务的每一次新增或变更,都会去数据库变更信息。
设置一个统一的任务管理器,专门负责动态任务的增删改查。
POM依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>dynamic-quartz</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>dynamic-quartz</name>
<description>动态定时任务管理</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- jdbc driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
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
<configuration>
<jmxConfigurator />
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern>
</layout>
</appender>
<logger name="org.springframework">
<level value="ERROR" />
</logger>
<logger name="org.mybatis">
<level value="ERROR" />
</logger>
<logger name="java.sql.Connection">
<level value="DEBUG" />
</logger>
<logger name="java.sql.Statement">
<level value="DEBUG" />
</logger>
<logger name="java.sql.PreparedStatement">
<level value="DEBUG" />
</logger>
<logger name="java.sql.ResultSet">
<level value="DEBUG"/>
</logger>
<logger name="org.apache.http">
<level value="INFO" />
</logger>
<logger name="org.quartz">
<level value="INFO" />
</logger>
<springProfile name="dev,test">
<root>
<level value="DEBUG" />
<appender-ref ref="stdout" />
</root>
</springProfile>
</configuration>
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<CronEntity> 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<CronEntity> 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<CronEntity> 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<Job> jobClass = null;
try {
//实例化具体的Job任务
jobClass = (Class<Job>) 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
对应的方法即可,必要时更新一下数据库就好啦。
以上是关于Spring Boot 定时任务,怎么实现任务动态增删启停?的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot 定时任务,怎么实现任务动态增删启停?
spring-boot-route(二十一)quartz实现动态定时任务
spring boot 整合 quartz 集群环境 实现 动态定时任务配置原