首先要配置我們的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 <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 3 <context:component-scan base-package="com.test"/>
掃描的是com.test這樣的包下的內容
下面需要接口和實現(我的這幾個java文件都是com.test的包下的
public interface IMyTestService { public void myTest(); }
1 @Component //import org.springframework.stereotype.Component; 2 public class MyTestServiceImpl implements IMyTestService { 3 @Scheduled(cron="0/5 * * * * ? ") //每5秒執行一次 4 @Override 5 public void 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觸發