SpringBoot注解@Scheduled定时任务的运行机制

文章讲述了如何在SpringBoot项目中使用`@Scheduled`注解创建定时任务,以及不同配置下任务执行的线程池效果。未配置时,任务共享线程可能导致效率低和阻塞;而配置ScheduledExecutorService后,可实现多线程并行执行,提高效率。
摘要由CSDN通过智能技术生成
1、使用@Scheduled注解创建两个任务测试运行
@Scheduled(cron = "0 0/1 * * * ?")
    public void test1() {
        log.info(Thread.currentThread().getName() + "- Scheduled1");
        try {
            Thread.sleep(1000 * 30);
        } catch (InterruptedException e) {
        }
        log.info(Thread.currentThread().getName() + "- Scheduled1");
    }
@Scheduled(cron = "0 0/1 * * * ?")
    public void test2() {
        log.info(Thread.currentThread().getName()+"-Scheduled2");
        try {
            Thread.sleep(1000 * 40);
        } catch (InterruptedException e) {
        }
        log.info(Thread.currentThread().getName()+"-Scheduled2");
    }
2、不做任何配置直接执行
2023-11-17 10:31:00.009  INFO 15660 --- [pool-1-thread-1] c.v.j.modules.controller.TestController  : pool-1-thread-1-Scheduled2
2023-11-17 10:31:40.020  INFO 15660 --- [pool-1-thread-1] c.v.j.modules.controller.TestController  : pool-1-thread-1-Scheduled1
2023-11-17 10:32:10.030  INFO 15660 --- [pool-1-thread-1] c.v.j.modules.controller.TestController  : pool-1-thread-1-Scheduled2
2023-11-17 10:33:00.014  INFO 15660 --- [pool-1-thread-1] c.v.j.modules.controller.TestController  : pool-1-thread-1-Scheduled1
3、配置ScheduledExecutorService线程池执行
/**
 * 执行周期性或定时任务
 */
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService() {
    return new ScheduledThreadPoolExecutor(10,
            new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
            new ThreadPoolExecutor.CallerRunsPolicy()) {
    };
}
2023-11-17 10:35:00.009  INFO 9588 --- [schedule-pool-2] c.v.j.modules.controller.TestController  : schedule-pool-2-Scheduled2
2023-11-17 10:35:00.009  INFO 9588 --- [schedule-pool-1] c.v.j.modules.controller.TestController  : schedule-pool-1-Scheduled1
2023-11-17 10:36:00.005  INFO 9588 --- [schedule-pool-1] c.v.j.modules.controller.TestController  : schedule-pool-1-Scheduled1
2023-11-17 10:36:00.005  INFO 9588 --- [schedule-pool-3] c.v.j.modules.controller.TestController  : schedule-pool-3-Scheduled2
4、结论

在不做配置的情况下,定时任务执行使用的线程是同一个(pool-1-thread-1),效率低下,当其中一个任务阻塞时,无法继续执行其他任务,或当前任务执行时间超过调度周期,也无法在下一周期时间立即执行任务;

修改Bean对象,配置ScheduledExecutorService线程池,可以开启多线程执行定时任务,在资源足够时不会相互影响,也不会;

建议 使用springboot项目时对ScheduledExecutorService线程池做自定义配置;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值