spring中@Scheduled定时任务执行时间不准确问题
一、问题背景
使用@Scheduled创建两个定时任务,其中一个1s执行。另一个1min执行。按分钟执行的出现了bug,我设定的规则如下:
@Async
@Scheduled(cron = "0 0/1 * * * ?")
public void workOfMin() {
logger.info("---------》work start...");
}
实际执行的时间不是每分钟00秒,而是随机的01~20之间。比如:每分钟的03、04、11秒执行任务。但是我要的结果是每分钟的00秒执行,必须精确。
二、解决方案
@SpringBootApplication
@EnableJpaRepositories(repositoryFactoryBeanClass = MyRepositoryFactoryBean.class)
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableScheduling
@Configuration
@EnableDiscoveryClient
@EnableFeignClients
@EnableCaching
public class Application extends DefaultApplication {
/**
*
*〈简述〉修复同一时间无法执行多个 定时任务问题
*〈详细描述〉
*/
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(50);
return taskScheduler;
}
/**
* 〈简述〉应用启动入口
* 〈详细描述〉
*
* @param args String[] 参数
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
创建一个@Bean方法,设置poolSize。原因是spring计划任务线程阻塞导致。