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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值