查看官方的计划任务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。