1. 程式人生 > >quartz 框架定時任務,使用spring @Scheduled註解執行定時任務

quartz 框架定時任務,使用spring @Scheduled註解執行定時任務

配置quartz 在spring中需要三個jar包:

quartz-1.6.5.jar、commons-collections-3.2.jar、commons-logging-1.1.jar

首先要配置我們的spring.xml

xmlns 多加下面的內容、

  1. xmlns:task="http://www.springframework.org/schema/task"

然後xsi:schemaLocation多加下面的內容、

  1. http://www.springframework.org/schema/task  
  2. http://www.springframework.org/schema/task/spring-task-3.1.xsd  

最後是我們的task任務掃描註解
  1. <task:annotation-driven/>

我的配置掃描位置是:
  1. <context:annotation-config/>
  2.     <beanclass="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
  3.     <context:component-scanbase-package="com.test"/>
掃描的是com.test這樣的包下的內容、

下面需要介面和實現(我的這幾個java檔案都是com.test的包下的、)

  1. publicinterface IMyTestService {  
  2.        publicvoid myTest();  
  3. }  


  1. @Component//import org.springframework.stereotype.Component;
  2. publicclass MyTestServiceImpl  implements IMyTestService {  
  3.       @Scheduled(cron="0/5 * *  * * ? ")   //每5秒執行一次
  4.       @Override
  5.       publicvoid myTest(){  
  6.             System.out.println("進入測試"
    );  
  7.       }  
  8. }  

執行後控制檯就會打印出   進入測試   了

需要注意的幾點:

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觸發