使用spring @Scheduled注解執(zhí)行定時任務(wù)

xmlns 多加下面的內(nèi)容

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

然后xsi:schemaLocation多加下面的內(nèi)容

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

最后是我們的task任務(wù)掃描注解

  <task:annotation-driven/>  

我的配置掃描位置是:

<context:annotation-config/>  
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>  
    <context:component-scan base-package="com.test"/>
@Component  //import org.springframework.stereotype.Component;  
public class MyTestServiceImpl  implements IMyTestService {  
      @Scheduled(cron="0/5 * *  * * ? ")   //每5秒執(zhí)行一次  
      @Override  
      public void myTest(){  
            System.out.println("進(jìn)入測試");  
      }  
}

1、spring的@Scheduled注解 需要寫在實(shí)現(xiàn)上、

2、 定時器的任務(wù)方法不能有返回值(如果有返回值,spring初始化的時候會告訴你有個錯誤、需要設(shè)定一個proxytargetclass的某個值為true、具體就去百度google吧)

3、實(shí)現(xiàn)類上要有組件的注解@Component

剩下的就是corn表達(dá)式了、具體使用以及參數(shù)請百度google、
下面只例出幾個式子

CRON表達(dá)式    含義 
"0 0 12 * * ?"    每天中午十二點(diǎn)觸發(fā) 
"0 15 10 ? * *"    每天早上10:15觸發(fā) 
"0 15 10 * * ?"    每天早上10:15觸發(fā) 
"0 15 10 * * ? *"    每天早上10:15觸發(fā) 
"0 15 10 * * ? 2005"    2005年的每天早上10:15觸發(fā) 
"0 * 14 * * ?"    每天從下午2點(diǎn)開始到2點(diǎn)59分每分鐘一次觸發(fā) 
"0 0/5 14 * * ?"    每天從下午2點(diǎn)開始到2:55分結(jié)束每5分鐘一次觸發(fā) 
"0 0/5 14,18 * * ?"    每天的下午2點(diǎn)至2:55和6點(diǎn)至6點(diǎn)55分兩個時間段內(nèi)每5分鐘一次觸發(fā) 
"0 0-5 14 * * ?"    每天14:00至14:05每分鐘一次觸發(fā) 
"0 10,44 14 ? 3 WED"    三月的每周三的14:10和14:44觸發(fā) 
"0 15 10 ? * MON-FRI"    每個周一、周二、周三、周四、周五的10:15觸發(fā) 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容