SpringBoot中定时任务开启多线程避免多任务堵塞

左手的ㄟ右手 2023-10-14 04:15 90阅读 0赞

场景

SpringBoot中定时任务与异步定时任务的实现:

SpringBoot中定时任务与异步定时任务的实现_霸道流氓气质的博客-CSDN博客

使用SpringBoot原生方式实现定时任务,已经开启多线程支持,以上是方式之一。

除此之外还可通过如下方式。

为什么Spring Boot 定时任务是单线程的?

查看注解@EnableScheduling源码可知

  1. protected void scheduleTasks() {
  2. if (this.taskScheduler == null) {
  3. this.localExecutor = Executors.newSingleThreadScheduledExecutor();
  4. this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
  5. }

b7cdc43ffc914134ab2837a980d2130c.png

![Image 1][]

为了验证单线程,所以编写模拟堵塞的测试方法

  1. import org.springframework.scheduling.annotation.EnableScheduling;
  2. import org.springframework.scheduling.annotation.Scheduled;
  3. import org.springframework.stereotype.Component;
  4. import java.time.LocalDateTime;
  5. import java.util.concurrent.TimeUnit;
  6. @Component
  7. @EnableScheduling
  8. public class TestTask {
  9. @Scheduled(fixedRateString = "15000")
  10. public void test1() throws InterruptedException {
  11. System.out.println("task1:"+LocalDateTime.now());
  12. //moni yanchi
  13. TimeUnit.SECONDS.sleep(10);
  14. }
  15. @Scheduled(fixedRateString = "3000")
  16. public void test2() {
  17. System.out.println("task2:"+LocalDateTime.now());
  18. }
  19. }

执行结果

ea5285b8d90d41f597f886bb48f99432.png

![Image 1][]

注:

博客:
霸道流氓气质_C#,架构之路,SpringBoot-CSDN博客

实现

1、方案一

Spring Boot quartz 已经提供了一个配置用来配置线程池的大小

添加如下配置

  1. spring:
  2. task:
  3. scheduling:
  4. pool:
  5. size: 10

再次进行堵塞测试发现正常

84d0f9f2a87d4784a69170b8f0341c39.png

![Image 1][]

2、方案二

重写SchedulingConfigurer#configureTasks()

  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.scheduling.annotation.SchedulingConfigurer;
  3. import org.springframework.scheduling.config.ScheduledTaskRegistrar;
  4. import java.util.concurrent.Executors;
  5. //直接实现SchedulingConfigurer这个接口,设置taskScheduler
  6. @Configuration
  7. public class ScheduleConfig implements SchedulingConfigurer {
  8. @Override
  9. public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
  10. taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
  11. }
  12. }

3、方案三

参考上面结合@Async的方式。

[Image 1]:

发表评论

表情:
评论列表 (有 0 条评论,90人围观)

还没有评论,来说两句吧...

相关阅读