使用spring @Scheduled註解運行定時任務、

曾經框架使用quartz框架運行定時調度問題、html

老大說這配置太麻煩、每個調度都需要多加在spring的配置中、java

能不能下降配置的量從而提升開發效率、spring

近期看了看spring的 scheduled的使用註解的方式進行調度、框架

感受很是方便、起碼配置的東西少了很是多、ide


因此留下來以備忘了、google


首先要配置咱們的spring.xmlcode


xmlns 多加如下的內容、component

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


而後xsi:schemaLocation多加如下的內容、xml

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

最後是咱們的task任務掃描註解

<task:annotation-driven/>

個人配置掃描位置是:

<context:annotation-config/>
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    <context:component-scan base-package="com.test"/>


掃描的是com.test這種包下的內容、

如下需要接口和實現(個人這幾個java文件都是com.test的包下的、)htm

public interface IMyTestService {
       public void myTest();
}



@Component  //import org.springframework.stereotype.Component;
public class MyTestServiceImpl  implements IMyTestService {
      @Scheduled(cron="0/5 * *  * * ? ")   //每5秒運行一次
      @Override
      public void myTest(){
            System.out.println("進入測試");
      }
}

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


需要注意的幾點:

一、spring的@Scheduled註解  需要寫在實現上、

二、 定時器的任務方法不能有返回值(假設有返回值,spring初始化的時候會告訴你有個錯誤、需要設定一個proxytargetclass的某個值爲true、詳細就去百度google吧)

三、實現類上要有組件的註解@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"    每個周1、周2、周3、周4、週五的10:15觸發 

相關文章
相關標籤/搜索