springboot + @scheduled 多任務併發

1、問題

項目採用springboot搭建,想給方法添加@Scheduled註解,實現兩個定時任務。但是運行發現,兩個task並無併發執行,而是執行完一個task纔會執行另一個。上代碼:html

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();
             }
         }
     }
}

運行發現任務沒有並行執行。spring

2、解決

給類添加註解@EnableAsync,並給方法添加註解@Async。springboot

@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();
             }
         }
     }
}

再次運行,發現兩個任務能夠併發執行了。併發

3、參考資料:

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

相關文章
相關標籤/搜索