spring boot @Scheduled未生效原因以及相关坑
在spring boot中,支持多种定时执行模式(cron, fixRate, fixDelay),在Application或者其他Autoconfig上增加@EnableScheduling注解开启。
然后在指定方法增加@Scheduled注解,如下:
@Scheduled(cron="0 0 0/1 * * ?") public void updateTime() {
current_log_time_appendix = sdf.format(new Date());
logger.info("日志文件切换, 切换后为:" + current_log_time_appendix);
}
需要注意的是,如果在多个函数上使用了@Scheduled,那么一定是一个执行完毕,才能排下一个。这往往不是我们想要的效果。此时需要在Scheduling配置类为schedule返回一个预定的线程池,如下:
@Configuration
@EnableScheduling
public class SchedulingConfiguration {
@Bean(destroyMethod = "shutdown")
public Executor taskScheduler() {
return Executors.newScheduledThreadPool(10);
}
}
完成之后,多个@Scheduled可以并发执行了,最高并发度是3,但是同一个@Schedule不会并发执行。