How to Enable Multithreaded Scheduled Tasks in Spring Boot
This article explains why Spring Boot's default scheduled tasks run on a single thread and demonstrates three practical ways to configure multithreaded scheduling using SchedulingConfigurer, application properties, and the @Async annotation with a custom thread pool.
The author introduces the problem that Spring Boot's @EnableScheduling creates a single‑threaded scheduler by default, as the ScheduledTaskRegistrar falls back to Executors.newSingleThreadScheduledExecutor() when no taskScheduler is provided.
To run scheduled tasks concurrently, three solutions are presented:
1. Implement SchedulingConfigurer and set a custom scheduler
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// Set a thread pool with 10 threads
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
}
}2. Configure the thread‑pool size via properties
spring.task.scheduling.pool.size=10Adding this line to application.properties or application.yml changes the scheduler to a pool of the specified size.
3. Combine @Async with a custom ThreadPoolTaskExecutor
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(4);
pool.setMaxPoolSize(6);
pool.setKeepAliveSeconds(120);
pool.setQueueCapacity(40);
pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
pool.setWaitForTasksToCompleteOnShutdown(true);
return pool;
}After defining the executor, annotate the scheduled method with both @Async and @Scheduled:
@Async
@Scheduled(cron = "0/2 * * * * ?")
public void test2() {
System.out.println("..................执行test2.................");
}The article concludes by asking readers which method they prefer and includes a promotional note encouraging followers to like, share, and subscribe for additional PDF resources on Spring Cloud, Spring Boot, and MyBatis.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
