Spring @SCHEDULED(CRON = "0 0 * * * ?")實現定時任務


Spring配置文件xmlns加入

xmlns:task="http://www.springframework.org/schema/task"

xsi:schemaLocation中加入

     http://www.springframework.org/schema/task
     http://www.springframework.org/schema/task/spring-task-3.0.xsd"

spring掃描注解的配置

<context:component-scan base-package="com.imwoniu.*" />

任務掃描注解

<task:executor id="executor" pool-size="5" />  
<task:scheduler id="scheduler" pool-size="10" />  
<task:annotation-driven executor="executor" scheduler="scheduler" />

代碼實現:

注解@Scheduled 可以作為一個觸發源添加到一個方法中,例如,以下的方法將以一個固定延遲時間5秒鍾調用一次執行,這個周期是以上一個調用任務的完成時間為基准,在上一個任務完成之后,5s后再次執行:

@Scheduled(fixedDelay = 5000)
public void doSomething() { 
    // something that should execute periodically
}

如果需要以固定速率執行,只要將注解中指定的屬性名稱改成fixedRate即可,以下方法將以一個固定速率5s來調用一次執行,這個周期是以上一個任務開始時間為基准,從上一任務開始執行后5s再次調用:

@Scheduled(fixedRate = 5000)
public void doSomething() { 
    // something that should execute periodically
}

 

如果簡單的定期調度不能滿足,那么cron表達式提供了可能

package com.imwoniu.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TaskDemo {
    
    @Scheduled(cron = "0 0 2 * * ?")  //每天凌晨兩點執行
        void doSomethingWith(){
            logger.info("定時任務開始......");
            long begin = System.currentTimeMillis();
        
            //執行數據庫操作了哦...
        
            long end = System.currentTimeMillis();
            logger.info("定時任務結束,共耗時:[" + (end-begin) / 1000 + "]秒");
    }
}

  

 

 

 

按順序依次為

秒(0~59)

分鍾(0~59)

小時(0~23)

天(月)(0~31,但是你需要考慮你月的天數)

月(0~11)

天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)

7.年份(1970-2099)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM