最近,遇到的一個需求,需要執行定時任務,每個一定時間需要執行某個方法
因為項目是SpringMVC的項目,所以使用的是Spring @Scheduled(由於quartz應用起來太麻煩,所以沒有采用)
接下來是應用步驟:
1、配置文件
1.1 需要配置一項 xmlns 如下:
xmlns:task="http://www.springframework.org/schema/task"
1.2 配置 xsi:schemaLocation(在applicationContext.xml中的beans屬性)
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
1.3 配置掃描 (在applicationContext.xml中的beans標簽內)
<!-- 定時器 注解 -->
<task:annotation-driven />
1.4 配置掃描路徑,做了定時總得讓Spring掃描到,對吧
<!-- 包的掃描路徑配置 -->
<context:component-scan base-package="com.wl"> <context:exclude-filter type="regex" expression=".common.*" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan>
1.5 創建任務類
類要加上@Component注解,Spring才能掃描到,另外fixedRate 和 fixedDelay 區別加在注釋上了
@Component
public class Task {
/**
* 每隔5分鍾執行
*/
@Scheduled(fixedRate = 1000*300)
public void task1(){
// do!
}
/**
* 上一個任務執行結束后5分鍾,再執行下一個任務
*/
@Scheduled(fixedDelay = 1000*300)
public void task2(){
// do!
}
/**
* 上一個任務執行結束后5分鍾,再執行下一個任務
*/
@Scheduled(fixedDelay = 1000*300)
public void task2(){
// do!
}
/** * 每隔5分鍾執行 */
@Scheduled(cron = 0 0/5 * * * ? )
public void task3(){ // do! }
}
附贈cron格式在線生成器
http://cron.qqe2.com/
