轉自 http://blog.lunhui.ren/archives/280
第一種方式
一. spring-context.xml配置加入
xmlns:task=”http://www.springframework.org/schema/task”
xsi:schemaLocation下面:http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
二. 繼續spring-context.xml配置加入
<!– 計划任務配置,用 @Service @Lazy(false)標注類,用@Scheduled(cron = “0 0 2 * * ?”)標注方法 –>
<task:executor id=”executor” pool-size=”10″/> <task:scheduler id=”scheduler” pool-size=”10″/>
<task:annotation-driven scheduler=”scheduler” executor=”executor” proxy-target-class=”true”/>
代碼基於注解形式的task
package com.thinkgem.jeesite.modules.sys.service; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; /** * Created by Administrator on 2016/6/22. */ @Service @Lazy(false) public class TaskJob2 { @Scheduled(cron="0/5 * * * * ? ") //每5秒執行一次 public void job1() { System.out.println("spring task 注解使用。。。任務進行中"); } }
發布項目即可在輸出行里看到輸出結果
第二種方式
繼續配置spring-context.xml加入
<task:scheduled-tasks> <task:scheduled ref="taskJob" method="job1" cron="0/5 * * * * ?"/> </task:scheduled-tasks>
task代碼
package com.thinkgem.jeesite.modules.sys.service; import org.springframework.stereotype.Service; @Service public class TaskJob { public void job1() { System.out.println("任務進行中。。。"); } }
發布項目即可在輸出行里看到輸出結果
附錄:摘自其他博文
cronExpression的配置說明,具體使用以及參數請百度google
字段 允許值 允許的特殊字符
秒 0-59 , – * /
分 0-59 , – * /
小時 0-23 , – * /
日期 1-31 , – * ? / L W C
月份 1-12 或者 JAN-DEC , – * /
星期 1-7 或者 SUN-SAT , – * ? / L C #
年(可選) 留空, 1970-2099 , – * /
– 區間
* 通配符
? 你不想設置那個字段
下面只例出幾個式子
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觸發