Spring Boot多线程环境下,解决多个定时任务冲突问题

37 篇文章 0 订阅
15 篇文章 0 订阅

问题引入

关于定时任务注解@Scheduled在之前的文章已经讲到,Spring Boot定时器默认的是单线程的。

但是问题就来了,如果在线程争夺资源后,某个线程需要比较长时间才能执行完,那其他的定时器怎么办,都只能进入等待状态,时间越久,累计等待的定时器越多,这就容易引起雪崩…

场景重现

我们清晰的看到执行结果都是scheduling-1。

如果在线程争夺资源后,某个线程需要比较长时间才能执行完,那其他的定时器怎么办,都只能进入等待状态,时间越久,累计等待的定时器越多,这就容易引起雪崩…

其实只需要添加一个配置类然后加注解就可以解决问题了

解决方案

添加注解
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WKjiIaeG-1641914203401)(https://www.cuizb.top/myblog/static/image/b8f6f4e6b6a5bda8c3b0477827d8007f.jpeg)]

具体代码如下 :

import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SchedulerTaskController {
    private Logger logger= LoggerFactory.getLogger(SchedulerTaskController.class);
    private static final SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
    private int count=0;
    @Scheduled(cron="*/6 * * * * ?")
    @Async("threadPoolTaskExecutor")
    public void process(){
        logger.info("英文:this is scheduler task runing "+(count++));
    }

    @Scheduled(fixedRate = 6000)
    @Async("threadPoolTaskExecutor")
    public void currentTime(){
        logger.info("中文:现在时间"+dateFormat.format(new Date()));
    }
}

配置类如下 :

具体代码如下 :

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**使用多线程的时候,往往需要创建Thread类,或者实现Runnable接口,如果要使用到线程池,我们还需要来创建Executors,
 * 在使用spring中,已经给我们做了很好的支持。只要要@EnableAsync就可以使用多线程
 * 通过spring给我们提供的ThreadPoolTaskExecutor就可以使用线程池。*/
//@Configuration 表示该类是一个配置类
@Configuration
@EnableAsync
//所有的定时任务都放在一个线程池中,定时任务启动时使用不同都线程。
public class TaskScheduleConfig {
    private static final int corePoolSize = 10;         // 默认线程数
    private static final int maxPoolSize = 100;       // 最大线程数
    private static final int keepAliveTime = 10;   // 允许线程空闲时间(单位:默认为秒),十秒后就把线程关闭
    private static final int queueCapacity = 200;   // 缓冲队列数
    private static final String threadNamePrefix = "it-is-threaddemo-"; // 线程池名前缀

    @Bean("threadPoolTaskExecutor") // bean的名称,默认为首字母小写的方法名
    public ThreadPoolTaskExecutor getDemoThread(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(keepAliveTime);
        executor.setKeepAliveSeconds(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);

        //线程池拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化
        executor.initialize();

        return executor;
    }
}

然后我们可以很清晰地看到

如上,也就解决了用多线程解决Springboot多定时器冲突的问题

更多文章和干货请移驾公众号和个人网站

本文作者:Java技术债务
原文链接:https://www.cuizb.top/myblog/article/1641914179
版权声明: 本博客所有文章除特别声明外,均采用 CC BY 3.0 CN协议进行许可。转载请署名作者且注明文章出处。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Java技术债务

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

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

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

打赏作者

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

抵扣说明:

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

余额充值