quartz 框架定時任務,使用spring @Scheduled註解執行定時任務
阿新 • • 發佈:2019-02-06
配置quartz 在spring中需要三個jar包:
quartz-1.6.5.jar、commons-collections-3.2.jar、commons-logging-1.1.jar
首先要配置我們的spring.xml
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.1.xsd
最後是我們的task任務掃描註解
- <task:annotation-driven/>
我的配置掃描位置是:
- <context:annotation-config/>
- <beanclass="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
- <context:component-scanbase-package="com.test"/>
下面需要介面和實現(我的這幾個java檔案都是com.test的包下的、)
- publicinterface IMyTestService {
- publicvoid myTest();
- }
- @Component//import org.springframework.stereotype.Component;
- publicclass MyTestServiceImpl implements IMyTestService {
- @Scheduled(cron="0/5 * * * * ? ") //每5秒執行一次
- @Override
- publicvoid myTest(){
- System.out.println("進入測試"
- }
- }
執行後控制檯就會打印出 進入測試 了
需要注意的幾點:
1、spring的@Scheduled註解 需要寫在實現上、
2、 定時器的任務方法不能有返回值(如果有返回值,spring初始化的時候會告訴你有個錯誤、需要設定一個proxytargetclass的某個值為true、具體就去百度google吧)
3、實現類上要有元件的註解@Component
剩下的就是corn表示式了、具體使用以及引數請百度google、
【秒】 【分】 【時】 【日】 【月】 【周】 【年】
下面只例出幾個式子
CRON表示式 含義"0 0 12 * * ?" 每天中午十二點觸發
"0 15 10 ? * *" 每天早上10:15觸發
"0 15 10 * * ?" 每天早上10:15觸發
"0 15 10 * * ? *" 每天早上10:15觸發
"0 15 10 * * ? 2005" 2005年的每天早上10:15觸發
"0 * 14 * * ?" 每天從下午2點開始到2點59分每分鐘一次觸發
"0 0/5 14 * * ?" 每天從下午2點開始到2:55分結束每5分鐘一次觸發
"0 0/5 14,18 * * ?" 每天的下午2點至2:55和6點至6點55分兩個時間段內每5分鐘一次觸發
"0 0-5 14 * * ?" 每天14:00至14:05每分鐘一次觸發
"0 10,44 14 ? 3 WED" 三月的每週三的14:10和14:44觸發
"0 15 10 ? * MON-FRI" 每個週一、週二、週三、週四、週五的10:15觸發