注解@Scheduled 可以作為一個(gè)觸發(fā)源添加到一個(gè)方法中,例如,以下的方法將以一個(gè)固定延遲時(shí)間5秒鐘調(diào)用一次執(zhí)行,這個(gè)周期是以上一個(gè)調(diào)用任務(wù)的完成時(shí)間為基準(zhǔn),在上一個(gè)任務(wù)完成之后,5s后再次執(zhí)行:
1 2 3 4 | @Scheduled (fixedDelay= 5000 ) public void doSomething() { // something that should execute periodically } |
如果需要以固定速率執(zhí)行,只要將注解中指定的屬性名稱改成fixedRate即可,以下方法將以一個(gè)固定速率5s來(lái)調(diào)用一次執(zhí)行,這個(gè)周期是以上一個(gè)任務(wù)開(kāi)始時(shí)間為基準(zhǔn),從上一任務(wù)開(kāi)始執(zhí)行后5s再次調(diào)用:
1 2 3 4 | @Scheduled (fixedRate= 5000 ) public void doSomething() { // something that should execute periodically } |
對(duì)于固定延遲和固定速率的任務(wù),可以指定一個(gè)初始延遲表示該方法在第一被調(diào)用執(zhí)行之前等待的毫秒數(shù):
1 2 3 4 | @Scheduled (initialDelay= 1000 , fixedRate= 5000 ) public void doSomething() { // something that should execute periodically } |
如果簡(jiǎn)單的定期調(diào)度不能滿足,那么cron表達(dá)式提供了可能。例如,下面的方法將只會(huì)在工作日?qǐng)?zhí)行:
1 2 3 4 | @Scheduled (cron= "*/5 * * * * MON-FRI" ) public void doSomething() { // something that should execute on weekdays only } |
還可以通過(guò)使用zone屬性來(lái)指定cron表達(dá)式被調(diào)用的時(shí)區(qū)。
注意:
1、spring的注解@Scheduled 需要寫(xiě)在實(shí)現(xiàn)方法上;
2、定時(shí)器的任務(wù)方法不能有返回值(如果有返回值,spring初始化的時(shí)候會(huì)告訴你有個(gè)錯(cuò)誤、需要設(shè)定一個(gè)proxytargetclass的某個(gè)值為true),不能指向任何的參數(shù);
3、如果該方法需要與應(yīng)用程序上下文的其他對(duì)象進(jìn)行交互,通常是通過(guò)依賴注入來(lái)實(shí)現(xiàn);
4、實(shí)現(xiàn)類上要有組件的注解@Component。
聯(lián)系客服