Spring Boot建立定時任務

2021-09-26 10:46:22 字數 1810 閱讀 9303

1,在spring boot的主類中加入@enablescheduling註解,啟用定時任務的配置,用於提醒springboot定時執行被標記的定時任務

示例;@enablescheduling

public static void main(string args) }

2.編寫定時任務的方法,給方法新增@scheduled註解即可。

示例:每天12點執行一次

@scheduled(cron = "0 0 12  * * ?")

public void testscheduling()

再看看@scheduled註解的描述:

@scheduled(cron = "",//cron表示式,用於編寫比如每星期的第一天,每分鐘,每小時,每一天,每一月,每一天等的機制,default ""

zone = "",//解析cron表示式的時區, default ""

fixeddelay = -1l,//方法之間以毫秒為單位執行方法,設定最後一次呼叫的結束時間以及下一次呼叫開始的時間。default -1

fixeddelaystring = "",//與fixeddelay同理,不過它是以毫秒為單位延遲乙個字串值。default ""

fixedrate = -1l,//週期地以毫秒為單位執行執行方法。default -1;

fixedratestring = "",//同fixedrate類似,default ""

initialdelay = -1l,//在第一次執行方法之前要延遲多少毫秒數,default -1

initialdelaystring = ""//同上

)

最常用的引數是cron ,使用cron 表示式可以建立很多定時規則。spring提供了相關的類(org.springframework.scheduling.support.cronsequencegenerator)用於解析cron表示式。

crontab表示式(允許使用萬用字元,對特殊字元的大小寫不敏感):

* * * * * * *

- - - - - - -

| | | | | | |

| | | | | | + 年[optional] 可以不寫, 1970-2099 , - * /

| | | | | +----- 星期幾 (1-7 或者 sun-sat , - * ? / l c # ) (sunday=0 or 7)

| | | | +---------- 月 (1 - 12 或者 jan-dec, - * /)

| | | +--------------- 日 (1 - 31 , - * / l w c ?)

| | +-------------------- 小時(0 - 23 , - * /)

| +------------------------- 分鐘(0 - 59 , - * /)

+------------------------------ 秒(0 - 59 , - * /)

(*):表示對應時間域的每乙個時刻,例如「每分鐘」;

(?):只在日和星期中使用,它通常指定為「無意義的值」,相當於點位符;

(-):表達乙個範圍,如在小時欄位中使用「10-12」,表示從10到12點;

(,):表達乙個列表值,如表示20分,30分和50分鐘,即為 20,30,50;

Spring Boot建立定時任務

在spring boot中編寫定時任務是很簡單的事情,下面通過實列來介紹下如何在spring boot中建立定時任務,實現每過三秒輸出一下當前時間。在spring boot的啟動類中加入 enablescheduling註解,啟動定時任務的配置。啟動類 實現類 在上面的入門例子中,使用了 sched...

spring boot 建立定時任務

1.scheduled建立定時任務,在springboot主類中加入 enablescheduling註解啟用定時任務的配置,備註 不支援集群,集群可以使用xxl job 2.首先建立乙個task包和乙個類,這個類中建立乙個方法來進行定時任務 3.需要在啟動類中啟動我們的定時任務 4.啟動之後我們來...

SpringBoot 定時任務

第一步 在啟動類中加入如下註解 enablescheduling public class public static void main string args 注意 enablescheduling必須加,否則無法開啟定時任務 第二步 建立定時任務 component public class ...