一、問題
項目采用springboot搭建,想給方法添加@Scheduled注解,實現兩個定時任務。可是運行發現,兩個task並沒有並發執行,而是執行完一個task才會執行另外一個。上代碼:
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。
@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
