当前位置: 首页 > news >正文

动态取消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 {
	@Autowired
    private 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();
			}
        }
	}
}

http://www.dtcms.com/a/106475.html

相关文章:

  • MySQL(1)
  • 【图像处理基石】什么是RAW格式?
  • React DndKit 实现类似slack 类别、频道拖动调整位置功能
  • # BERT架构及详解
  • C# 中实现不同程序进程间消息交互
  • 【Linux网络#18】:深入理解select多路转接:传统I/O复用的基石
  • ETCD --- lock详解
  • JAVASE(十五)正则表达式
  • 2024年最新版零基础详细Java知识笔记【反射】⑩
  • Python实现 MCP 客户端调用(高德地图 MCP 服务)查询天气工具示例
  • Linux系统
  • Oracle 23ai Vector Search 系列之3 集成嵌入生成模型(Embedding Model)到数据库示例,以及常见错误
  • 16变量命名风格
  • windows部署docker
  • electron-update + nginx热更新
  • 【深度学习:进阶篇】--2.1.多分类与TensorFlow
  • 2025 年山东危化品经营单位考试攻略分享​
  • 二分查找与二叉树中序遍历——面试算法
  • OpenCV单窗口显示多图片
  • MySQL分组的时候遇到ONLY_FULL_GROUP_BY报错和解决
  • html+css+javaScript实现一个扫雷游戏
  • MATLAB 代码学习
  • Spring Boot 3.0 + JDK 17整合SpringDoc实战指南
  • 清明假期在即
  • 5G网络中SIB System Information Blocks系统信息块
  • 安美数字酒店宽带运营系统存在SQL注入漏洞
  • 云端商标管理系统如何确保用户数据安全?
  • 《永动之城的舞者》
  • Spring Boot 集成 Redis 连续操作键值对示例
  • MySQL性能:存储过程+触发器基础实战攻略