SpringBoot2.x整合定時任務和異步任務處理
一.項目環境
springboot2.x本身已經集成了定時任務模塊和異步任務,可以直接使用
二.springboot常用定時任務配置
1.在啟動類上使用注解@EnableScheduling開啟定時任務,使用@EnableAsync開啟異步任務
@SpringBootApplication //一個注解頂下面3個 @EnableScheduling //開啟定時任務 @EnableAsync //開啟異步任務 public class XdclassApplication { public static void main(String[] args) { SpringApplication.run(XdclassApplication.class, args); } }
2.使用注解@Schedule聲明這是一個定時任務,Springboot啟動會掃描到該注解並標記為定時任務
@Component public class TestTask { @Scheduled(cron="*/1 * * * * *") public void sum2(){ System.out.println("cron 每秒 當前時間:"+new Date()); } }
3.使用@Asyn聲明這是一個異步任務的方法,如果在類上使用該注解,則該類下所有方法都是異步任務的方法
@Component @Async public class AsyncTask { public void task1() throws InterruptedException{ long begin = System.currentTimeMillis(); Thread.sleep(1000L); long end = System.currentTimeMillis(); System.out.println("任務1耗時="+(end-begin)); } public void task2() throws InterruptedException{ long begin = System.currentTimeMillis(); Thread.sleep(2000L); long end = System.currentTimeMillis(); System.out.println("任務2耗時="+(end-begin)); } public void task3() throws InterruptedException{ long begin = System.currentTimeMillis(); Thread.sleep(3000L); long end = System.currentTimeMillis(); System.out.println("任務3耗時="+(end-begin)); } //獲取異步結果 public Future<String> task4() throws InterruptedException{ long begin = System.currentTimeMillis(); Thread.sleep(2000L); long end = System.currentTimeMillis(); System.out.println("任務4耗時="+(end-begin)); return new AsyncResult<String>("任務4"); } public Future<String> task5() throws InterruptedException{ long begin = System.currentTimeMillis(); Thread.sleep(3000L); long end = System.currentTimeMillis(); System.out.println("任務5耗時="+(end-begin)); return new AsyncResult<String>("任務5"); } public Future<String> task6() throws InterruptedException{ long begin = System.currentTimeMillis(); Thread.sleep(1000L); long end = System.currentTimeMillis(); System.out.println("任務6耗時="+(end-begin)); return new AsyncResult<String>("任務6"); } }
測試
@RestController @RequestMapping("/api/v1") public class UserController { @Autowired private AsyncTask task; @GetMapping("async_task") public JsonData exeTask() throws InterruptedException{ long begin = System.currentTimeMillis(); // task.task1(); // task.task2(); // task.task3(); Future<String> task4 = task.task4(); Future<String> task5 = task.task5(); Future<String> task6 = task.task6(); //這里死循環讓主線程掛起,目的是為了計算其他異步任務的執行任務的耗時 for(;;){ if (task4.isDone() && task5.isDone() && task6.isDone()) { break; } } long end = System.currentTimeMillis(); long total = end-begin; System.out.println("執行總耗時="+total); return JsonData.buildSuccess(total); } }