SpringBoot 定時任務的使用

2022-07-04 09:33:10 字數 816 閱讀 1787

springboot自帶了定時任務的功能,不需要額外新增依賴。

1、在引導類上加@enablescheduling

@enablescheduling

//啟用定時任務

public

class

public

static

void

main(string args)

}2、在要定時執行的方法上加@scheduled

這裡我們隨便寫乙個類,隨便寫乙個方法

@component

public

class

test

}

@scheduled將一方法標識為定時方法。

cron指定時間間隔,6部分:從前往後依次為 秒分時日月年,越來越大,該部分要設定就寫成0/n的形式,不設定就寫成*。示例:

0/5  *  *  *   *  *    每隔5s執行一次

*  0/5  *  *  *  *    每隔5s執行一次

0/30  0/1  *  *  *  *    間隔不是1min30s,而是30s。只能設定乙個部分,若設定多個部分,只有第乙個設定的部分有效

0/90  *  *  *  *  *     間隔不是90s,而是60s。若數值超過合法值,會自動用最大值代替。比如秒、分的最大值是60,時的最大值是24,日的最大值是31,月的最大值12。

只能設定整的。比如說要設定秒,那只能設定為0-60s;設定分,只能設定1-60min;不能設定為分+秒,不能帶零頭,必須是整的。

定時方法每隔指定時間,系統會自動呼叫、執行,不需要我們手動呼叫。

SpringBoot 定時任務

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

Spring boot定時任務

最近做專案,需要使用定時任務,半個小時去更新redis資料,於是便學習了一下經驗。希望可以幫到你們。定時任務可使用三種 created by fx on 2017 9 4.component allargsconstructor public class featuredatatask 實現乙個任務...

Spring boot 定時任務

1.在啟動類上加 enablescheduling註解 package com.example.demo import org.springframework.scheduling.annotation.enablescheduling enablescheduling public static ...