目的: 終止 @Scheduled 定時(shí)任務(wù)
@Slf4j
@Component
public class ScheduleUtils {
/**
* 得到BeanPostProcessor,用于終止定時(shí)任務(wù)
*/
@Autowired
private ScheduledAnnotationBeanPostProcessor postProcessor;
/**
* 根據(jù) methodName 終止定時(shí)任務(wù)
*
* @param methodName
*/
public void cancelScheduledTask(String methodName) {
Set<ScheduledTask> tasks = postProcessor.getScheduledTasks();
// 從所有定時(shí)任務(wù)中找出 methodName 并取消掉
tasks.stream().forEach(task -> {
Task t = task.getTask();
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) t.getRunnable();
if (Objects.equals(runnable.getMethod().getName(), methodName)) {
// 調(diào)用postProcessBeforeDestruction()方法掌呜,將task移除并cancel
postProcessor.postProcessBeforeDestruction(runnable.getTarget(), methodName);
log.error("定時(shí)任務(wù)[{}],被終止", methodName);
}
});
}
}