Does spring @Scheduled annotated methods runs on different threads?
For completeness, code below shows the simplest possible way to configure scheduler with java config:
@Configuration@EnableSchedulingpublic class SpringConfiguration { @Bean(destroyMethod = "shutdown") public Executor taskScheduler() { return Executors.newScheduledThreadPool(5); } ...
When more control is desired, a @Configuration
class may implement SchedulingConfigurer
.
The documentation about scheduling says:
If you do not provide a pool-size attribute, the default thread pool will only have a single thread.
So if you have many scheduled tasks, you should configure the scheduler, as explained in the documentation, to have a pool with more threads, to make sure one long task doesn't delay all the other ones.
A method annotated with @Scheduled
is meant to be run separately, on a different thread at a moment in time.
If you haven't provided a TaskScheduler
in your configuration, Spring will use
Executors.newSingleThreadScheduledExecutor();
which returns an ScheduledExecutorService
that runs on a single thread. As such, if you have multiple @Scheduled
methods, although they are scheduled, they each need to wait for the thread to complete executing the previous task. You might keep getting bigger and bigger delays as the the queue fills up faster than it empties out.
Make sure you configure your scheduling environment with an appropriate amount of threads.