Does spring @Scheduled annotated methods runs on different threads?
Solution 1:
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.
Solution 2:
For completeness, 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
.
Solution 3:
UPDATE 2019 (still valid in 2022)
There is also a property you can set in your application properties file that increases the pool size:
spring.task.scheduling.pool.size=10
Seems to be there since Spring Boot 2.1.0.