Search code examples
springspring-scheduled

Why does Spring @schedule annotation not run at exact times each day?


I have a method annotated using spring schedule as follows:

@Scheduled(cron = "0 0 0 * * *", zone = "Europe/Amsterdam").

What I have noticed is that the time this job runs sometimes differ. For example a snippet from the log:

2021-09-18T23:09:46,479 INFO  [ScheduledJob]
2021-09-19T22:00:00,005 INFO  [ScheduledJob] 
2021-09-20T23:07:40,760 INFO  [ScheduledJob] 

I can understand if the execution time differs by seconds, but sometimes it differs by up to an hour

Why won't the @scheduled annotation not trigger at consistent times?


Solution

  • Try increasing the number of threads available as follows: spring.task.scheduling.pool.size = 5

    Or via JavaConfig:

    public class ThreadPoolTaskSchedulerConfig {
    
        @Bean
        public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
            ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
            threadPoolTaskScheduler.setPoolSize(5);
            threadPoolTaskScheduler.setThreadNamePrefix("Whatever name you want to give it for debugging purposes");
            return threadPoolTaskScheduler;
        }
    }
    

    I used 5, but you might decide this is not enough and maybe try with more.