Springboot配置多线程定时任务Scheduled

技术交流QQ群933925017
Springboot配置多线程定时任务Scheduled springboot默认定时任务是单线程的,需要配置成多线程

一.为什么需要配置多线程定时任务& 多线程定时任务的配置使用场景

springboot中通过注解 @Scheduled 注解的方法都是一个定时执行的任务, 默认都是单线程的,就算是多个定时任务也是在同一个单线程(scheduled-1)中运行, 如果其中某一个定时任务产生了阻塞,那么会导致项目中其他所有的定时任务线程都不执行。后果非常严重,故而需要配置多线程定时任务。

2.多线程定时任务配置类
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;

@Configuration
@EnableScheduling // 开启定时任务
public class ScheduledConfiguration implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("scheduled@");// 设置定时任务线程名称的前缀
        int corePoolSize  = 10; // 设置定时任务的核心线程数
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize,executor));
    }
}
3.测试
// 定时任务1,用于测试
    @Scheduled(fixedDelay = 1000)
    public void test1() throws IOException {
        Thread thread = Thread.currentThread();
       log.info("test1定时任务处理线程 : "+thread.getName());
    }
    // 定时任务2,用于测试
    @Scheduled(fixedDelay =1000)
    public void test2() throws IOException {
        Thread thread = Thread.currentThread();
        log.info("test2定时任务处理线程开始休眠 : "+thread.getName());
        try {
            Thread.sleep(100000000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
4.测试之后发现1s之后线程将不会在执行了
5.增加配置类之后会继续执行
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值