1. 程式人生 > >SpringBoot 定時任務@Scheduled詳解

SpringBoot 定時任務@Scheduled詳解

@Scheduled是Spring的一個定時任務註解,通過註解配置就能夠輕量級的定時任務,簡單方便。
## <一>註解使用說明 ##
package org.springframework.scheduling.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import
java.lang.annotation.Target; import org.springframework.scheduling.annotation.Schedules; @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Repeatable(Schedules.class) public @interface Scheduled { //根據石英錶達式執行 String cron() default ""; //指定時間地區,預設系統時間地區
String zone() default ""; //上一次執行成功後多少毫秒後執行 long fixedDelay() default -1L; //同上,只不過值是String形式 String fixedDelayString() default ""; //固定速率執行 long fixedRate() default -1L; //同上,只不過值是String形式 String fixedRateString() default ""; //延遲多少毫秒後執行 long initialDelay() default
-1L; //同上,只不過值是String形式 String initialDelayString() default ""; }
//石英錶達式(每一分鐘執行一次),具體的就不在這描述啦
@Scheduled(cron = "0 0/1 * * * ?") 
public void run() {
  //執行程式碼
}
//定義一個按一定頻率執行的定時任務,每隔1分鐘執行一次,延遲1秒執行
    @Scheduled(fixedRate = 1000 * 60,initialDelay = 1000)
    public void run() {
    //執行程式碼
}
//上一個任務完成後,兩分鐘後執行
    @Scheduled(fixedDelay = 1000 * 120)
    public void run() {
    //執行程式碼
}
## <二>執行原理##
這篇部落格對執行原理講解的很詳細。
(http://blog.csdn.net/DanLei824/article/details/52149685)

## <三>序列,並行##
spring task Scheduled預設的執行緒數是1,多個任務相當於序列,但是對於某個任務來說還是序列,設定了執行緒數也沒用,當前job1沒執行完前,下個job1就沒法執行,但是不影響job2。
要想並行執行多個job,就得修改配置
<task:annotation-driven scheduler="scheduler" mode="proxy"/>  
<task:scheduler id="scheduler" pool-size="10"/> 

或者繼承SchedulingConfigurer類並重寫其方法即可,如下:

@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean(destroyMethod="shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(10);
    }
}