JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

多线程实现Spring定时任务@Scheduled

wys521 2024-11-23 23:46:03 精选教程 33 ℃ 0 评论

前言

技术的入门大多比较简单,把别人的代码复制过来,删删改改,基本也就能实现个功能,查看个API大概也就知道如何实现几个功能,但是,如果对一项技术了解的足够深入,就要知道一个技术的优缺点,以及他存在的问题,这些就需要大量的时间及思考,疾风知劲草,只有足够了解才能临危不惧,才能在如疾风般强劲的bug来临时微微一笑,绝对不倒!

一 定时任务调度注解@Scheduled

这个注解是spring定时任务中的主角,他包含几种类型

@Scheduled(fixedDelay = 2000) 
@Scheduled(fixedRate = 2000) 
@Scheduled(initialDelay = 1000, fixedDelay = 2000)   
@Scheduled(cron = "*/5 * * * * *")
复制代码

使用过定时任务的童鞋应该都是使用过以上集中注解,现在简单介绍一下

 @Scheduled(fixedDelay = 2000)   等上一个任务执行完2s后执行
 @Scheduled(fixedRate = 2000)    从上一个任务开始后的2s,下一个任务进行执行
 @Scheduled(initialDelay = 1000, fixedDelay = 2000)  方法不会立即执行 要等initialDelay后再执行
 @Scheduled(cron = "*/5 * * * * *")   选定时间进行执行
复制代码

下面重点说一下 @Scheduled(fixedRate = 2000) 他的说明是从上一个任务开始后的2s,下一个任务进行执行,但是真的如此吗? 我们来验证一下

  1. 创建一个定时任务类,及定时任务方法 /** * Spring的定时任务 */ @Component @EnableScheduling public class ScheduleJob { @Autowired private TaskService taskService; /** * 和上一个方法的开始和下一个方法的开始固定是2s * 这种方法适合任务之间是独立的 */ @Scheduled(fixedRate = 2000) public void fixedRateTaskR() { taskService.sayHello("fixedRate"); } 复制代码
  2. 创建接口 public interface TaskService { void sayHello(String type); } 复制代码
  3. 具体实现类 @Override public void sayHello(String type) { try { long startTime = System.currentTimeMillis() / 1000; System.out.println(type + " => " + startTime + " - 任务开始"); System.out.println(type + " => " + "任务执行中"); Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } } 复制代码

我在执行的任务线程进行延时操作,每次执行都会休眠5s,如果每两秒执行一次那么,方法的间隔时间打印出来就是2s,我们执行下,看下结果

fixedRate => 1632646194 - 任务开始
fixedRate => 任务执行中
fixedRate => 1632646197 - 任务开始
fixedRate => 任务执行中
fixedRate => 1632646199 - 任务开始
复制代码

结果很明显是间隔了5s执行一次,而不是2s,说明要等上一个任务执行完下一个任务才会执行,哇塞不哇塞! 既然存在这样的问题,那如果我就要不等上一个任务执行完,就是要2s执行一次能不能干! 当然能干!现在就干!

二 使用@Async实现异步调度

  1. 建立spring线程池
/**
 * @author 千云
 * @Description spring线程池配置类
 * @Date 2021/8/3
 */
@EnableAsync
@Configuration
public class SendMsgThreadPoolConfig {

    @Bean("schedule")
    public Executor schduleTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("schedule-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
复制代码
  1. 为异步调度方法指定线程池
   @Override
    @Async("schedule")
    public void sayHello(String type) {
        try {
            long startTime = System.currentTimeMillis() / 1000;
            System.out.println(type + " => " + startTime + " - 任务开始");

            System.out.println(type + " => " + "任务执行中");
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
复制代码

我们再执行以下,看下输出结果

fixedRate => 任务执行中
fixedRate => 1632646666 - 任务开始
fixedRate => 任务执行中
fixedRate => 1632646668 - 任务开始
fixedRate => 任务执行中
fixedRate => 1632646671 - 任务开始
fixedRate => 任务执行中
fixedRate => 1632646673 - 任务开始
复制代码

看下控制台,现在的时间间隔就是2s,2s,3s,小伙伴可能就会觉得奇怪了,为啥出现了3s的间隔,这是咋回事,这是因为我们创建的线程池,我们线程池的核心线程和最大线程数都是2个,每两秒执行一次,前4s两个线程就被占满了,第三个任务执行时,要进行等待,因为第一个任务线程的休眠时间是5s,那么第三个任务线程在等待1s后会执行,这就是间隔3s的原因,验证一下,将线程数修改为3个。看下控制台输出

fixedRate => 1632647147 - 任务开始
fixedRate => 任务执行中
fixedRate => 1632647149 - 任务开始
fixedRate => 任务执行中
fixedRate => 1632647151 - 任务开始
fixedRate => 任务执行中
复制代码

这是执行时间间隔就为2s了。


作者:千云
链接:https://juejin.cn/post/7012166808702550030
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表