SpringBoot開啟異步任務只需要兩步配置:
1、在主類上加上注解@EnableAsync開啟異步功能
2、在service層的方法上加上注解@Async指定調用方法時是異步的
SpringBoot開啟定時任務也只需兩步配置:
1、在主類上加上注解@EnableScheduling開啟定時功能
2、在service層的方法上@Scheduled(cron = "0/5 * * * * MON-SAT")指定定時調用該方法
具體任務如下:
1、在主類上加上注解@EnableAsync開啟異步功能
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class SpringBoot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot04TaskApplication.class, args);
}
}
2、在service層的方法上加上注解@Async指定調用方法時是異步的
package com.example.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async
public void hello(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("處理數據中");
}
}
為了進行測試,添加controller層代碼如下:
package com.example.controller;
import com.example.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();
return "成功";
}
}
頁面訪問進行測試,發現沒有加異步注解的時候,5秒后控制台打印處理數據中,頁面也是需要5秒后才能顯示成功;
而使用了異步注解之后,頁面可直接顯示成功,5秒后控制台打印處理數據中,說明調用service的異步方法時是單獨啟用了一個線程。
1、在主類上加上注解@EnableScheduling開啟定時功能
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class SpringBoot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot04TaskApplication.class, args);
}
}
2、在service層的方法上@Scheduled(cron = "0/5 * * * * MON-SAT")指定定時調用該方法
package com.example.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledService {
//second, minute, hour, day of month, month, and day of week.
//"0 * * * * MON-FRI"
//0到4秒都運行
// @Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
// @Scheduled(cron = "0-4 * * * * MON-SAT")
//0秒開始,每隔5秒運行一次
@Scheduled(cron = "0/5 * * * * MON-SAT")
public void hello(){
System.out.println("hello.......");
}
}
如有理解不到之處,望指正;