Search code examples
javaspringscheduled-tasks

Does spring @Scheduled annotated methods runs on different threads?


I have several methods annotated with @Scheduled(fixedDelay=10000).

In the application context, I have this annotation-driven setup:

<task:annotation-driven />

The problem is, sometimes some of the method executions get delayed by seconds and even minutes.

I'm assuming that even if a method takes a while to finish executing, the other methods would still execute. So I don't understand the delay.

Is there a way to maybe lessen or even remove the delay?


Solution

  • Spring 4.x

    Code below shows the simplest possible way to configure scheduler with java config:

    @Configuration
    @EnableScheduling
    public class SpringConfiguration {
    
        @Bean(destroyMethod = "shutdown")
        public Executor taskScheduler() {
            return Executors.newScheduledThreadPool(5);
        }
        ...
    

    When more control is desired, a @Configuration class may implement SchedulingConfigurer.

    Spring Boot

    In Spring Boot there is a simple property to configure the thread pool size:

    spring.task.scheduling.pool.size=5