Scenes
Implementation of timing tasks and asynchronous timing tasks in SpringBoot:
Realization of timing tasks and asynchronous timing tasks in SpringBoot - Programmer Sought
Use the SpringBoot native method to implement timing tasks, and multi-thread support has been enabled. The above is one of the methods.
In addition, the following methods can also be used.
Why are Spring Boot timing tasks single-threaded?
Check the annotation @EnableScheduling source code to see
protected void scheduleTasks() {
if (this.taskScheduler == null) {
this.localExecutor = Executors.newSingleThreadScheduledExecutor();
this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
}
In order to verify single thread, write a test method that simulates blocking
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
@Component
@EnableScheduling
public class TestTask {
@Scheduled(fixedRateString = "15000")
public void test1() throws InterruptedException {
System.out.println("task1:"+LocalDateTime.now());
//moni yanchi
TimeUnit.SECONDS.sleep(10);
}
@Scheduled(fixedRateString = "3000")
public void test2() {
System.out.println("task2:"+LocalDateTime.now());
}
}
Results of the
Note:
Blog:
Domineering Rogue Temperament_C#, Architecture Road, SpringBoot-CSDN Blog
accomplish
1. Option 1
Spring Boot quartz already provides a configuration to configure the size of the thread pool
Add the following configuration
spring:
task:
scheduling:
pool:
size: 10
The blockage test was performed again and found to be normal
2. Scheme 2
重写SchedulingConfigurer#configureTasks()
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executors;
//直接实现SchedulingConfigurer这个接口,设置taskScheduler
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
}
}
3. Scheme 3
Refer to the way of combining @Async above.