What is the solution to the blocking problem of multiple scheduled tasks in Spring Boot?
Spring Boot multiple scheduled task blocking solution is what, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
Preface
Today, let's talk about how to start multithreaded timing tasks in Spring Boot.
Why are Spring Boot scheduled tasks single-threaded?
If you want to explain why, you must start with the source code and find the ScheduledTaskRegistrar class directly from the @ EnableScheduling annotation. There is a piece of code like this:
Protected void scheduleTasks () {if (this.taskScheduler = = null) {this.localExecutor = Executors.newSingleThreadScheduledExecutor (); this.taskScheduler = new ConcurrentTaskScheduler (this.localExecutor);}}
If taskScheduler is null, create a single-threaded thread pool: Executors.newSingleThreadScheduledExecutor ().
How to configure multithreaded timing tasks?
The following are three scenarios for configuring scheduled tasks under multithreading.
1. Rewrite SchedulingConfigurer#configureTasks ()
Directly implement the API SchedulingConfigurer and set taskScheduler. The code is as follows:
@ Configurationpublic class ScheduleConfig implements SchedulingConfigurer {@ Override public void configureTasks (ScheduledTaskRegistrar taskRegistrar) {/ / set a 10-length scheduled task thread pool taskRegistrar.setScheduler (Executors.newScheduledThreadPool (10));}} 2. Open it through configuration
Spring Boot quartz has provided a configuration to configure the size of the thread pool, as follows
Spring.task.scheduling.pool.size=10
Just add the above configuration to the configuration file to take effect!
3. Combine @ Async
The @ Async annotation has been used to start asynchronous tasks. You must configure the thread pool before using the @ Async annotation, as follows:
@ Bean public ThreadPoolTaskExecutor taskExecutor () {ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor (); poolTaskExecutor.setCorePoolSize (4); poolTaskExecutor.setMaxPoolSize (6); / / set thread active time (seconds) poolTaskExecutor.setKeepAliveSeconds (120); / / set queue capacity poolTaskExecutor.setQueueCapacity (40); poolTaskExecutor.setRejectedExecutionHandler (new ThreadPoolExecutor.CallerRunsPolicy ()) / / wait for all tasks to finish before closing the thread pool poolTaskExecutor.setWaitForTasksToCompleteOnShutdown (true); return poolTaskExecutor;}
Then mark the @ Async annotation on the @ Scheduled method to implement the multithreaded timing task, as follows:
@ Async @ Scheduled (cron = "0can2 *?") Public void test2 () {System.out.println (". Execute test2.");} is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.