日常開發(fā)中需要制定一些定時任務(wù),在使用spring boot就很好解決這個問題,現(xiàn)在pom文件里面配置好依賴項,如果對pom不了解的,可以點這里查看。
1.pom包配置
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
初始化之后,我們在spring boot的入口類Application.java中,允許支持schedule
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
定時任務(wù)1
@Component
public class SchedulerTask {
private int count=0;
@Scheduled(cron="*/6 * * * * ?")
private void process(){
System.out.println("this is scheduler task runing "+(count++));
}
}
定時任務(wù)2
@Component
public class Scheduler2Task {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
System.out.println("現(xiàn)在時間:" + dateFormat.format(new Date()));
}
}
結(jié)果如下:
this is scheduler task runing 0
現(xiàn)在時間:09:44:17
this is scheduler task runing 1
現(xiàn)在時間:09:44:23
this is scheduler task runing 2
現(xiàn)在時間:09:44:29
this is scheduler task runing 3
現(xiàn)在時間:09:44:35
參數(shù)說明:
@Scheduled 參數(shù)可以接受兩種定時的設(shè)置,一種是我們常用的cron=”*/6 * * * * ?”,一種是 fixedRate = 6000,兩種都表示每隔六秒打印一下內(nèi)容。
fixedRate 說明
- @Scheduled(fixedRate = 6000) :上一次開始執(zhí)行時間點之后6秒再執(zhí)行;
- @Scheduled(fixedDelay = 6000) :上一次執(zhí)行完畢時間點之后6秒再執(zhí)行;
- @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲1秒后執(zhí)行,之后按fixedRate的規(guī)則每6秒執(zhí)行一次.
而還有一類定時任務(wù),比如是每天的3點15分執(zhí)行,那么我們就需要用另外一種方式:cron表達式
cron一共有7位,但是最后一位是年,可以留空,所以我們可以寫6位:
* 第一位,表示秒,取值0-59
* 第二位,表示分,取值0-59
* 第三位,表示小時,取值0-23
* 第四位,日期天/日,取值1-31
* 第五位,日期月份,取值1-12
* 第六位,星期,取值1-7,星期一,星期二...,注:不是第1周,第二周的意思
另外:1表示星期天,2表示星期一。
* 第7為,年份,可以留空,取值1970-2099
cron中,還有一些特殊的符號,含義如下:
(*)星號:可以理解為每的意思,每秒,每分,每天,每月,每年...
(?)問號:問號只能出現(xiàn)在日期和星期這兩個位置,表示這個位置的值不確定,每天3點執(zhí)行,所以第六位星期的位置,我們是不需要關(guān)注的,就是不確定的值。同時:日期和星期是兩個相互排斥的元素,通過問號來表明不指定值。比如,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/6 * * * * ? 每隔6s執(zhí)行
0 0 3 * * ? 每天3點執(zhí)行
0 5 3 * * ? 每天3點5分執(zhí)行
0 5 3 ? * * 每天3點5分執(zhí)行,與上面作用相同
0 5/10 3 * * ? 每天3點的 5分,15分,25分,35分,45分,55分這幾個時間點執(zhí)行
0 10 3 ? * 1 每周星期天,3點10分 執(zhí)行,注:1表示星期天
0 10 3 ? * 1#3 每個月的第三個星期,星期天 執(zhí)行,#號只能出現(xiàn)在星期的位置