適用的工具是:Schedule
集成步驟:
1、開啟Schedule支持
package com.jsoft.springboottest.springboottest1; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; /** * Hello world! * */ @SpringBootApplication @EnableScheduling public class App { public static void main( String[] args ) { SpringApplication.run(App.class, args); } }
2、使用
package com.jsoft.springboottest.springboottest1.controller; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { private static final Logger logger = LoggerFactory.getLogger(TestController.class); @Scheduled(fixedRate = 5000) public void reportCurrentTime() { logger.info("每隔五秒鍾執行一次: " + new Date().toString()); } @Scheduled(cron = "15 52 21 ? * *") public void fixTimeExecution() { logger.info("在指定時間執行" + new Date().toString()); } @RequestMapping("/show") public String show(){ return "Hello World"; } }
說明:支持Linux的cron表達式。
cron表達式
參數:
* 第一位,表示秒,取值0-59 * 第二位,表示分,取值0-59 * 第三位,表示小時,取值0-23 * 第四位,日期天/日,取值1-31 * 第五位,日期月份,取值1-12 * 第六位,星期,取值1-7,星期一,星期二...,注:不是第1周,第二周的意思,另外:1表示星期天,2表示星期一。 * 第7為,年份,可以留空,取值1970-2099 (*)星號:可以理解為每的意思,每秒,每分,每天,每月,每年... (?)問號:問號只能出現在日期和星期這兩個位置,表示這個位置的值不確定,每天3點執行,所以第六位星期的位置,我們是不需要關注的,就是不確定的值。同時:日期和星期是兩個相互排斥的元素,通過問號來表明不指定值。比如,1月10日,比如是星期1,如果在星期的位置是另指定星期二,就前后沖突矛盾了。 (-)減號:表達一個范圍,如在小時字段中使用“10-12”,則表示從10到12點,即10,11,12 (,)逗號:表達一個列表值,如在星期字段中使用“1,2,4”,則表示星期一,星期二,星期四 (/)斜杠:如:x/y,x是開始值,y是步長,比如在第一位(秒) 0/15就是,從0秒開始,每15秒,最后就是0,15,30,45,60 另:*/y,等同於0/y 示例: 0 0 3 * * ? 每天3點執行 0 5 3 * * ? 每天3點5分執行 0 5 3 ? * * 每天3點5分執行,與上面作用相同 0 5/10 3 * * ? 每天3點的 5分,15分,25分,35分,45分,55分這幾個時間點執行 0 10 3 ? * 1 每周星期天,3點10分 執行,注:1表示星期天 0 10 3 ? * 1#3 每個月的第三個星期,星期天 執行,#號只能出現在星期的位置
示例工程:https://github.com/easonjim/5_java_example/tree/master/springboottest/springboottest8
參考:
http://www.importnew.com/27287.html(以上內容轉自此篇文章)