Spring之@Scheduled

使用spring自带的轻量级调度系统进行任务调度和终止


1.TimedTask 任务调度

代码如下:

@Component
public class TimedTask {

    //得到Bean的后置处理器ScheduledAnnotationBeanPostProcessor,用于终止定时任务
    @Autowired
    private ScheduledAnnotationBeanPostProcessor postProcessor;

    private Integer y = 5;

    // cron生成器在线生成网址: https://cron.qqe2.com/
    @Scheduled(cron = "0/5 * * * * ? ")
    public void printTask(){
        y--;
        System.out.println(y);
        if(y == 0){
            System.out.println("结束此次定时任务");
            cancelScheduledTasks();
        }
    }

    /**
     * 通过 ScheduledAnnotationBeanPostProcessor 终止所有定时任务
     * 非常暴力,不推荐使用
     */
    public void cancelScheduledTasks() {
        // 拿到所有的task(带包装)
        Set<ScheduledTask> tasks = postProcessor.getScheduledTasks();
        if(null != tasks && tasks.size() > 0){
            tasks.stream().forEach(task -> {
                Task t = task.getTask();
                ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) t.getRunnable();
                //task所关联的对象,就是带@Scheduled方法的类
                Object taskObject = runnable.getTarget();
                // 调用postProcessBeforeDestruction()方法,将task移除并cancel
                postProcessor.postProcessBeforeDestruction(taskObject, "scheduledTasks");
            });
        }
    }
}

2.主启动类开启@EnableScheduling

代码如下:

@EnableScheduling
@SpringBootApplication
public class AppTest {

    public static void main(String[] args) {
        SpringApplication.run(AppTest.class, args);
    }
}

3.执行结果

4
3
2
1
0
结束此次定时任务
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值