[Java学习思路与工具]springboot官方demo@Scheduled计划任务

查看官方的计划任务demo

1、实现定时任务只需要两步:”@EnableScheduling标注启动类“和"@Scheduled标注方法"

@SpringBootApplication
@EnableScheduling
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@Component
public class TestTask {
    @Scheduled(fixedRate = 1000)
    public void ok() {
    }
}

2、springboot如何加载计划任务:
首先,计划任务是spring-context包中的内容,无需其他依赖。
我们选中Scheduled注解,先使用**[idea的Edit / FInd / Find Usages]**工具,可以看到使用它的地方:在这里插入图片描述
我们找到了这个ScheduledAnnotationBeanPostProcessor类,也就是在我们计划任务bean加载后,调用了此方法,看源码可以知道,此时为@Scheduled方法创建了Runnable实例。

然后,我们还有一种办法追踪源码执行过程,就是Debug,我们给@Scheduled方法设置断点。

Debug方式启动程序。

然后查看Idea下边的Debug面板:
在这里插入图片描述
顺藤摸瓜,从前面创建Runnable的方法,我们可以看到run对象最终封装成了task放在了ScheduledAnnotationBeanPostProcessor的Map<Object, Set> scheduledTasks变量中,没有后续动作。

当我们看到onApplicationEvent及finishRegistration时,我们就知道了,当task的执行是通过event消息来触发的。

3、总结一下计划任务的运行。
a.spring的applicationContext.refresh方法加载Bean时,加载我们的定时任务bean。
b.spring加载完成后,发送event消息,我们开始执行task。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值