springboot + @scheduled 多任务并发

本文介绍如何在SpringBoot项目中使用@Scheduled注解实现定时任务,并通过添加@EnableAsync和@Async注解使多个定时任务并发执行的方法。

一、问题


项目采用springboot搭建,想给方法添加@Scheduled注解,实现两个定时任务。可是运行发现,两个task并没有并发执行,而是执行完一个task才会执行另外一个。上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package  com.autohome.contentplatform.tasks;
 
import  org.springframework.beans.factory.annotation.Configurable;
import  org.springframework.scheduling.annotation.EnableScheduling;
import  org.springframework.scheduling.annotation.Scheduled;
import  org.springframework.stereotype.Component;
 
@Component
@Configurable
@EnableScheduling
public  class  task1 {
      @Scheduled (cron =  "0/5 * *  * * ? " )
      public  void  startSchedule() {
          System.out.println( "===========1=>" );
          try  {
              for ( int  i= 1 ;i<= 10 ;i++){
                  System.out.println( "=1==>" +i);
                  Thread.sleep( 1000 );
              }
          catch  (InterruptedException e) {
              e.printStackTrace();
          }
      }
      @Scheduled (cron =  "0/5 * *  * * ? " )
      public  void  startSchedule2() {
          for ( int  i= 1 ;i<= 10 ;i++){
              System.out.println( "=2==>" +i);
              try  {
                  Thread.sleep( 1000 );
              catch  (InterruptedException e) {
                  e.printStackTrace();
              }
          }
      }
}

 

运行发现任务没有并行执行。

二、解决


给类添加注解@EnableAsync,并给方法添加注解@Async。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Component
@Configurable
@EnableScheduling
@EnableAsync
public  class  DemoTask {
      @Async
      @Scheduled (cron =  "0/5 * *  * * ? " )
      public  void  startSchedule() {
          System.out.println( "===========1=>" );
          try  {
              for ( int  i= 1 ;i<= 10 ;i++){
                  System.out.println( "=1==>" +i);
                  Thread.sleep( 1000 );
              }
          catch  (InterruptedException e) {
              e.printStackTrace();
          }
      }
 
     @Async
      @Scheduled (cron =  "0/5 * *  * * ? " )
      public  void  startSchedule2() {
          for ( int  i= 1 ;i<= 10 ;i++){
              System.out.println( "=2==>" +i);
              try  {
                  Thread.sleep( 1000 );
              catch  (InterruptedException e) {
                  e.printStackTrace();
              }
          }
      }
}

 

再次运行,发现两个任务可以并发执行了。

三、参考资料:

https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html

 






    本文转自 陈敬(Cathy) 博客园博客,原文链接:http://www.cnblogs.com/janes/p/8085654.html,如需转载请自行联系原作者



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值