spring boot
通过注解@EnableScheduling
和@Scheduled
实现的是静态定时任务,不能动态添加、停止、修改等.
本文通过ThreadPoolTaskScheduler
实现定时任务动态增删改.
- 创建
ThreadPoolTaskScheduler
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(10);
threadPoolTaskScheduler.setRemoveOnCancelPolicy(true);
return threadPoolTaskScheduler;
}
- 创建一个全局任务记录表
@Data
public class Tasks {
public static Map<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();
}
- 创建一个任务类
public class MyRunnable implements Runnable {
private String id;
public MyRunnable(String id) {
this.id = id;
}
@Override
public void run() {
System.out.println("id: " + this.id + " - " + new Date());
}
}
- 通过接口启动/删除/修改定时任务
任务的元数据信息可以保存在数据库中.
@RestController
public class DynamicTask {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
// 增加一个带id的定时任务
@RequestMapping("/start")
public String startCron(@RequestParam("id") String id) {
if (Tasks.tasks.containsKey(id)) {
return "exist";
}
ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new MyRunnable(id), new CronTrigger("0/5 * * * * *"));
Tasks.tasks.put(id, future);
return "start";
}
//根据id删除一个定时任务
@RequestMapping("/stop")
public String stop(@RequestParam("id") String id) {
if (!Tasks.tasks.containsKey(id)) {
return "not exist";
}
Tasks.tasks.get(id).cancel(true);
Tasks.tasks.remove(id);
return "stop";
}
//根据id修改定时任务
@RequestMapping("/change")
public String start(@RequestParam("id") String id) {
stopCron(id);// 先停止,在开启.
ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new MyRunnable(id), new CronTrigger("*/10 * * * * *"));
Tasks.tasks.put(id, future);
return "change";
}
}