欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > 动态取消Spring Boot通过注解@EnableScheduling启动的定时任务

动态取消Spring Boot通过注解@EnableScheduling启动的定时任务

2025/6/17 21:14:09 来源:https://blog.csdn.net/shenweihong/article/details/146958434  浏览:    关键词:动态取消Spring Boot通过注解@EnableScheduling启动的定时任务

原理:

通过注解组件ScheduledAnnotationBeanPostProcessor ,获取到所有的通过注解@Scheduled(包括@EnableScheduling)注解启动的ScheduledTask集合,然后在集合里面遍历查找ScheduledTask对应的包名,以此判断是否关闭。

代码:

package com.shenweihong.main;import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;@EnableScheduling
@Component
public class TimerFileWatch {@Autowiredprivate ScheduledAnnotationBeanPostProcessor mBeanPostProcessor;@Scheduled(fixedRate = 320 * 1)public void WatchFileChange() {stopTask();}private void stopTask() {Set<ScheduledTask> tasks = mBeanPostProcessor.getScheduledTasks();Iterator<ScheduledTask> it = tasks.iterator();ScheduledTask scheduledTask = null;String strTmp = null;while (it.hasNext()) {scheduledTask = it.next();if (scheduledTask == null) {continue;}System.out.println("scheduledTask = " + scheduledTask.toString());strTmp = scheduledTask.toString();if (strTmp != null && strTmp.equals("com.shenweihong.main.TimerFileWatch.WatchFileChange")) {scheduledTask.cancel();}}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词