好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

一、前言

技术的入门大多比较简单,把别人的代码复制过来,删删改改,基本也就能实现个功能,查看个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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

/**

  * Spring的定时任务

  */

@Component

@EnableScheduling

public class ScheduleJob {

     @Autowired

     private TaskService taskService;

     /**

      * 和上一个方法的开始和下一个方法的开始固定是2s

      * 这种方法适合任务之间是独立的

      */

     @Scheduled (fixedRate = 2000 )

     public void fixedRateTaskR() {

         taskService.sayHello( "fixedRate" );

     }

创建接口:

?

1

2

3

public interface TaskService {

     void sayHello(String type);

}

具体实现类:

?

1

2

3

4

5

6

7

8

9

10

11

12

@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实现异步调度

建立spring线程池

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

/**

  * @Description spring线程池配置类

  */

@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

2

3

4

5

6

7

8

9

10

11

12

@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了。

到此这篇关于Spring多线程通过@Scheduled实现定时任务的文章就介绍到这了,更多相关Spring定时任务内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://juejin.cn/post/7012166808702550030

查看更多关于Spring多线程通过@Scheduled实现定时任务的详细内容...

  阅读:16次