spring boot定时器异步配置

SpringBoot 定时器异步配置

本文简单记录一下spring schedule 的异步配置,当业务执行时间大于定时器的定时时间的时候,schedule默认的单线程是不够用的,会导致定时的事件丢失。

启动类

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableAsync // 开启异步
@EnableCaching
@EnableScheduling
public class JucAppliction {
    public static void main(String[] args) {
        SpringApplication.run(JucAppliction.class,args);
    }
}

配置线程池

@Configuration
@EnableAsync
//定时任务调用一个线程池中的线程。
public class ScheduleConfig {
    private static final int corePoolSize = 15;       		// 核心线程数(默认线程数)
    private static final int maxPoolSize = 100;			    // 最大线程数
    private static final int keepAliveTime = 10;			// 允许线程空闲时间(单位:默认为秒)
    private static final int queueCapacity = 200;			// 缓冲队列数
    private static final String threadNamePrefix = "my-threadPool"; // 线程池名前缀

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

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

}

任务执行类

@Service
public class TaskService {

    @Scheduled(fixedRate = 1000)
    @Async
    void execute() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "--------------" + LocalTime.now() + "开始执行");
        Thread.sleep(5000);
        System.out.println(Thread.currentThread().getName() + "--------------" + "执行完毕");
    }
}

执行效果图
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值