目的: 终止 @Scheduled 定时任务
@Slf4j
@Component
public class ScheduleUtils {
/**
* 得到BeanPostProcessor,用于终止定时任务
*/
@Autowired
private ScheduledAnnotationBeanPostProcessor postProcessor;
/**
* 根据 methodName 终止定时任务
*
* @param methodName
*/
public void cancelScheduledTask(String methodName) {
Set<ScheduledTask> tasks = postProcessor.getScheduledTasks();
// 从所有定时任务中找出 methodName 并取消掉
tasks.stream().forEach(task -> {
Task t = task.getTask();
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) t.getRunnable();
if (Objects.equals(runnable.getMethod().getName(), methodName)) {
// 调用postProcessBeforeDestruction()方法,将task移除并cancel
postProcessor.postProcessBeforeDestruction(runnable.getTarget(), methodName);
log.error("定时任务[{}],被终止", methodName);
}
});
}
}