@Data
public class Cron {
@TableId(type = IdType.AUTO)
private Integer id;
@TableField(value = "send_time")
private String sendTime;
@TableField(value = "status")
private Integer status;
@TableField(value = "cron_str")
private String cronStr;
}
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for cron
-- ----------------------------
DROP TABLE IF EXISTS `cron`;
CREATE TABLE `cron` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '表主键',
`send_time` varchar(6) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '发送时间',
`status` int(2) DEFAULT NULL COMMENT '状态(0:停止使用,1:使用)',
`cron_str` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '表达式',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 18 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
SET FOREIGN_KEY_CHECKS = 1;
/**
* 添加执行定时任务的线程池配置类
* @author 81509
*/
@Configuration
public class SchedulerThreadPoolConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
// 定时任务执行线程池核心线程数
taskScheduler.setPoolSize(10);
//设置任务注册器的调度器
taskScheduler.setRemoveOnCancelPolicy(true);
//设置线程名称前缀
taskScheduler.setThreadNamePrefix("SchedulerThreadPool-");
return taskScheduler;
}
}
public final class ScheduledTask {
volatile ScheduledFuture<?> future;
/**
* 取消定时任务
*/
public void cancel() {
ScheduledFuture<?> future = this.future;
if (future != null) {
future.cancel(true);
}
}
}
public class SchedulingRunnable implements Runnable {
private Cron cron;
public SchedulingRunnable(Cron cron) {
this.cron = cron;
}
@Override
public void run() {
//执行任务
System.out.println("执行任务");
}
}
/**
* 添加定时任务注册类,用来增加、删除定时任务。
* @author 81509
*/
@Component
public class CronTaskRegistrar implements DisposableBean {
private final Map<Integer, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);
@Autowired
private TaskScheduler taskScheduler;
public TaskScheduler getScheduler() {
return this.taskScheduler;
}
public void addCronTask(Integer cronId,Runnable task, String cronExpression) {
addCronTask(cronId,new CronTask(task, cronExpression));
}
public void addCronTask(Integer cronId,CronTask cronTask) {
if (cronTask != null) {
if (this.scheduledTasks.containsKey(cronId)) {
removeCronTask(cronId);
}
this.scheduledTasks.put(cronId, scheduleCronTask(cronTask));
}
}
public void removeCronTask(Integer cronId) {
ScheduledTask scheduledTask = this.scheduledTasks.remove(cronId);
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
public class ScheduleConfig implements CommandLineRunner {
@Autowired
private CronTaskRegistrar taskRegistrar;
@Autowired
private CronController cronController;
@Override
public void run(String... args) throws Exception {
List<Cron> crons = cronController.findCrons();
for (Cron cron : crons) {
if (cron.getStatus() == 1) {
SchedulingRunnable task = new SchedulingRunnable(cron);
taskRegistrar.addCronTask(cron.getId(), task, cron.getCronStr());
}
}
}
}
@RestController
public class CronController {
@Autowired
private ICronService cronService;
@Autowired
private CronTaskRegistrar taskRegistrar;
//添加定时任务
@PostMapping("/saveCron")
public HttpResult save() {
Cron cron = new Cron();
//每天八点一十五分
cron.setCronStr("0 15 08 * * ? ");
cron.setStatus(1);
cron.setSendTime("08:15");
boolean success = cronService.saveOrUpdate(cron);
if (!success) {
return HttpResult.error("定时任务保存失败");
}
if (cron.getStatus() == 1) {
SchedulingRunnable task = new SchedulingRunnable(cron);
taskRegistrar.removeCronTask(cron.getId());
taskRegistrar.addCronTask(cron.getId(),task, cron.getCronStr());
}
if (cron.getStatus() == 0) {
taskRegistrar.removeCronTask(cron.getId());
}
return HttpResult.ok("定时任务保存成功");
}
//删除定时任务
@PostMapping("/deleteCron")
public HttpResult delete(Integer cronId) {
if (cronId != null) {
Cron cron = cronService.getById(cronId);
boolean remove = cronService.removeById(cronId);
if (remove) {
taskRegistrar.removeCronTask(cronId);
}
return HttpResult.ok("定时任务删除成功");
}
return HttpResult.error("传入数据为空");
}
public List<Cron> findCrons() {
return cronService.list();
}
}
至此Spring Boot实现动态增加、删除、修改、停止定时任务就已实现
Git项目地址:https://github.com/815090488/dynamicScheduler