最近使用spring运行定时任务时发现每次都运行俩遍,而且俩次是不一样的线程
@Component
public class TimeDemo1 {
@Scheduled(cron = "0/3 * * * * ?")
public void demo2() {
System.out.println(Thread.currentThread().getName() + " 1111");
System.out.println("===================");
}
一开始以为是线程的问题,于是在容器中添加了任务线程池
@Bean
public TaskScheduler taskScheduler(){
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
return threadPoolTaskScheduler;
}
但是依旧运行俩遍,后来网上查找资料发现可能是因为配置内容加载了俩遍。
第一次:web容器启动的时候,读取applicationContext.xml文件时,会加载一次。
第二次:Spring本身会加载applicationContext.xml一次。
于是将定时任务配置类单独拎出来,然后解决了。
@EnableScheduling
@Configuration
public class TaskConfig {
}



