Spring通過註解使用定時器(已經驗證)
阿新 • • 發佈:2019-01-28
先需要在springMVC的配置檔案中,配置定時器的掃描註解
?1 2 |
<!-- 定時器開關 開始-->
< task:annotation-driven />
|
定時器的實現程式碼
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.test.control.base;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component;
@Component
public class SpringTimerTest {
/**
* 啟動時執行一次,之後每隔3秒執行一次
*/
@Scheduled (fixedRate = 1000 * 3 )
public void print() {
System.out.println( "timer running..." );
}
/**
* 定時啟動。每天凌晨 16:19 執行一次
*/
@Scheduled (cron = "0 19 16 * * *" )
public void show() {
System.out.println( "定時器啟動..." );
}
}
|
最後寫個main方法測試下
?1 2 3 |
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext( "springmvcContext.xml" );
}
|