現在由於開發要求,需要用到定時器的地方可能比較多。在這裏把使用spring定時器的基礎方法分享出來,希望能給大家帶來幫助。
方式一:使用配置方式
導入jar包
在spring核心配置文件中添加命名空間和xmlschema地址
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"
定義一個定時器類,使用@service註解(理論上component、repository等註解都可以。和我們在service層使用@service不使用@component一樣,這裏建議這樣使用)
import org.springframework.stereotype.Service;
/**
* 定時器
* @author huangzhilin
*
*/
@Service
public class Task {
public void task1() {
System.out.println("開始任務......");
}
}
然後在spring配置文件中配置該定時器
<!-- 配置spring自動掃描 -->
<context:component-scan base-package="com.jk"></context:component-scan>
<!-- 定時器 -->
<task:scheduled-tasks>
<!-- task 爲我們的Task類,task1爲計劃方法,cron表達式定義計劃週期 -->
<task:scheduled ref="task" method="task1" cron="0/3 * * * * ?"/>
</task:scheduled-tasks>
本地測試一下:
public class Test {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("src/main/resourse/applicationContext.xml");
}
}
方式二:使用註解
同配置方式,導入jar包,添加命名空間和xmlschema地址後,spring配置文件中配置
<task:executor id="executor" pool-size="1" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
然後在自定義類中註解
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class TaskAnno {
@Scheduled(cron="0/3 * * * * ?")
public void task(){
System.out.println("開始任務......");
}
}
本地測試:
public class Test {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("src/main/resourse/applicationContext.xml");
}
}
上面提到的cron表達式本身是一個字符串,字符串一5或6個空格隔開,分爲6或7個域,都有着不同的含義。
Seconds Minutes Hours DayofMonth Month DayofWeek Year或
Seconds Minutes Hours DayofMonth Month DayofWeek
具體的編寫方式可自行Google或百度。就像上面出現的 "0/3 * * * * ?"表示每3秒執行一次計劃任務。下面給出一個在線cron表達式生成網頁,感興趣的可以看啊看看