spring 定時任務(wù) @Scheduled

@Scheduled 源碼如下:

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
    String CRON_DISABLED = "-";
    String cron() default "";
    String zone() default "";
    long fixedDelay() default -1L;
    String fixedDelayString() default "";
    long fixedRate() default -1L;
    String fixedRateString() default "";
    long initialDelay() default -1L;
    String initialDelayString() default "";
    TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
}

使用@Scheduled 首先需要開啟定時任務(wù) 需要在config類上添加@EnableScheduling注解
例如:

@Configuration
@EnableScheduling
public class AppConfig {
}

@Scheduled 可以在方法及注解類上使用
例如

// 上一次開始執(zhí)行時間點之后 6 秒再執(zhí)行。
@Scheduled(fixedRate = 6000)
public void doSomething() {
    // something that should run periodically
}
// 上一次執(zhí)行完畢時間點之后 6 秒再執(zhí)行。
@Scheduled(fixedDelay = 6000)
public void doSomething() {
    // something that should run periodically
}
@Scheduled 默認的時間單位為毫秒 可以通過timeUnit屬性修改

// 上一次執(zhí)行完畢時間點之后 1分鐘再執(zhí)行。
@Scheduled(fixedDelay = 1,timeUnit = TimeUnit.SECONDS)
public void doSomething() {
    // something that should run periodically
}
initialDelay表示首次延遲多長時間后執(zhí)行,單位ms,之后按照cron/fixedRate/fixedRateString/fixedDelay/fixedDelayString指定的規(guī)則執(zhí)行,需要指定其中一個規(guī)則.
@Scheduled(initialDelay=1000,fixedRate=1000) //首次運行延遲1s

cron是@Scheduled的一個參數(shù),是一個字符串,以5個空格隔開,只允許6個域(注意不是7個,7個直接會報錯),分別表示秒,分,時,日,月,周.


image.png

image.png

@Scheduled(cron = "0 * * * 1 SAT") //每年的1月的所有周六的所有0秒時間執(zhí)行
@Scheduled(cron = "0 0 0 1 Jan ?") //每年的1月的1日的0時0分0秒執(zhí)行

還可以使用zone屬性指定在哪個時區(qū)解析cron表達式。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容