SpringBoot solves blocking of multiple timing tasks
This article introduces how to enable multi-threaded timing tasks in Spring Boot?
Why are Spring Boot timing tasks single-threaded?
If you want to explain why, you must start from the source code and start directly from the annotation @EnableScheduling, and found thisScheduledTaskRegistrarClass, there is a piece of code as follows:
protected void scheduleTasks() { if ( == null) { = (); = new ConcurrentTaskScheduler(); } }
If taskScheduler is null, a single-threaded thread pool is created: ().
How to configure multithreaded timing tasks?
The following are three solutions to configure timing tasks under multi-threading.
1. Rewrite SchedulingConfigurer#configureTasks()
Directly implement the SchedulingConfigurer interface, set up the taskScheduler, the code is as follows:
@Configuration public class ScheduleConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { //Set a timed task thread pool of 10 length ((10)); } }
2. Turn on through configuration
Spring Boot quartz has provided a configuration to configure the size of the thread pool, as follows;
=10
Just add the above configuration to the configuration file to take effect!
3. Combined with @Async
The @Async annotation has been used to enable asynchronous tasks. Before using the @Async annotation, you must first configure the thread pool. The configuration is as follows:
@Bean public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor(); (4); (6); // Set thread activity time (seconds) (120); // Set queue capacity (40); (new ()); // Wait until all tasks are finished before closing the thread pool (true); return poolTaskExecutor; }
Then mark the @Async annotation on the @Scheduled method to implement multi-threaded timing tasks. The code is as follows:
@Async @Scheduled(cron = "0/2 * * * * ? ") public void test2() { (".........Execute test2............"); }
Summarize
This article introduces three solutions to implement multi-threaded timing tasks in Spring Boot. Which one do you like?
The above is personal experience. I hope you can give you a reference and I hope you can support me more.