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

场景

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

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

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

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

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

查看注解@EnableScheduling源码可知

    protected void scheduleTasks() {
        if (this.taskScheduler == null) {
            this.localExecutor = Executors.newSingleThreadScheduledExecutor();
            this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
        }

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

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());
    }
}

执行结果

注:

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

实现

1、方案一

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

添加如下配置

spring:
  task:
    scheduling:
      pool:
        size: 10

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

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、方案三

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值