动态取消@Scheduled定时任务

目的: 终止 @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);
            }
        });
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容