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 + "]秒"); } }