最近公司上線了抽獎的活動,活動需求
1:每天凌晨更新狀態,實現自動開啟和關閉活動
2:活動結束自動抽取中獎號碼
在這里提供spring的定時調度功能
1:首先是配置文件
在你的web.xml中,查看配置文件的路徑,路徑很多的時候 比如 classpath*:spring-*.xml這種
只需要在其中一個spring-xx.xml配置
<!-- 加載所有的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
那么就在applicationContext.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.2.xsd
最后是我們的task任務掃描注解
<task:annotation-driven/>
掃描方式1
<context:annotation-config/> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <context:component-scan base-package="com.test"/>
注:使用了<context:component-scan />就不需要<context:annotation-config/>了
這里我們使用scan掃描即方式2
<context:component-scan base-package="com.test" />
同時,之前存在掃描controller service dao這樣的注解的時候,若定時任務存在於該掃描包內,也是不用加的
接下來就是代碼的實現(代碼在掃描包下)
提供簡單事例
@Component public class LotteryBatch { //設置活動開啟結束狀態修改定時檢測 //每天00:00到00:10每分鍾執行一次 @Scheduled(cron="0 0-10 0 * * ?") public void checkStatus(){ System.out.println("11"); } }
需要注意幾點,這幾點摘抄自小牛的博客,具體沒有試過
需要注意的幾點:
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觸發
