註解支援定時任務和非同步處理
阿新 • • 發佈:2019-02-09
Spring支援使用註解開啟定時任務和非同步方法執行
為了支援@Scheduled 和 @Async 註解,需要在你的@Configuration類上加 @EnableScheduling
和@EnableAsync
註解
@EnableScheduling @EnableAsync @SpringBootApplication public class SpringBootApiApplication { public static void main(String[] args) { SpringApplication.run(SpringBootApiApplication.class,args); } }
使用@Scheduled註解
@Component
public class HelloJob {
@Scheduled(cron = "0/10 * * * * * ")
public void hello(){
System.out.println("hello");
}
}
除了時間表達式,還有其他的方式,比如:
@Scheduled(fixedDelay=5000) ---固定延遲每5秒執行一次,從上次執行完成開始測量時間
@Scheduled(fixedRate=5000) ---兩次任務執行時間間隔為5秒
使用@Async
可以在方法上使用@Async註解,以便非同步呼叫該方法,呼叫者將在呼叫時立刻返回,實際的執行已經提交給Spring taskExecutor的任務中。
@Async
void doSomething() {
// this will be executed asynchronously
}
方法可使用引數
@Async
void doSomething(String s) {
// this will be executed asynchronously
}
還可以非同步呼叫返回值的方法,這些方法需要具有Future型別的返回值。
@Async
Future<String> returnSomething(int i) {
// this will be executed asynchronously
}
@Async不能與生命週期回撥一起使用,例如@PostConstruct,如果要非同步初始化Spring Bean,必須使用單獨的Spring bean,然後在目標方法上使用@Async註解
public class SampleBeanImpl implements SampleBean {
@Async
void doSomething() {
// ...
}
}
public class SampleBeanInitializer {
private final SampleBean bean;
public SampleBeanInitializer(SampleBean bean) {
this.bean = bean;
}
@PostConstruct
public void initialize() {
bean.doSomething();
}
}
當@Async方法具有Future型別返回值時,很容易管理在方法執行期間丟擲的異常,因為在呼叫get結果時會丟擲此異常。 但是,對於void返回型別,異常未被捕獲且無法傳輸。 對於這些情況,可以提供AsyncUncaughtExceptionHandler來處理此類異常。
public class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
// handle exception
}
}