註解支持定時任務和異步處理

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
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章