1. 方式 1:通过Spring 的ScheduledAnnotationBeanPostProcessor 类终止定时任务
代码示例:
/*得到BeanPostProcessor,用于终止定时任务*/
@Autowired
private ScheduledAnnotationBeanPostProcessor postProcessor;
/**
* 通过 ScheduledAnnotationBeanPostProcessor 终止所有定时任务
*/
public void cancelScheduledTasks() {
// 拿到所有的task(带包装)
Set<ScheduledTask> tasks = postProcessor.getScheduledTasks();
Set<Object> rawTasks = new HashSet<>(tasks.size());
for (ScheduledTask task : tasks) {
Task t = task.getTask();
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) t.getRunnable();
Object taskObject = runnable.getTarget();
// 将task所关联的对象放到Set中(就是带@Scheduled方法的类)
rawTasks.add(taskObject);
}
// 调用postProcessBeforeDestruction()方法,将task移除并cancel
for (Object obj : rawTasks) {
postProcessor.postProcessBeforeDestruction(obj, "scheduledTasks");
}
}
详情参考: 重启Spring Scheduler的正确打开方式