最近在项目中,发现我的定时计划类,未按设定的计划执行@Scheduled(initialDelay = 10000, fixedDelay = 5 * 1000),按说应该每隔五秒中执行一次,但是跟踪日志发现,有时两次执行中间隔时间不是五秒,出现了间隔一分钟,甚至三四分钟的情况。
后来查询资料发现,springboot项目中,默认是只要一个线程去执行定时计划的,当项目中定时器多起来,这是该线程如果执行别的定时任务阻塞,则会导致其余的定时任务执行时间间隔变长。解决办法也很简单,就是初始一个定时任务执行线程池。
@Configuration public class ScheduleThreadPool implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { log.info("*****************开始加载定时任务线程池**********************"); Method[] methods = BatchProperties.Job.class.getMethods(); int defaultPoolSize = 10; int corePoolSize = 0; if (methods != null && methods.length > 0) { for (Method method : methods) { Scheduled annotation = method.getAnnotation(Scheduled.class); if (annotation != null) { corePoolSize++; } } if (defaultPoolSize > corePoolSize) corePoolSize = defaultPoolSize; } taskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize)); log.info("*****************加载定时任务线程池完毕**********************"); } }