springboot中的定時(shí)任務(wù)
1.在啟動(dòng)類上加入@EnableScheduling開啟定時(shí)任務(wù)
@ComponentScan(value = "com.haijunyin.springbootdemo")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableAsync
@EnableScheduling //開啟定時(shí)任務(wù)
public class SpringbootdemoSimpleApplication extends SpringBootServletInitializer{
2.新建類HelloJob.java
package com.haijunyin.springbootdemo.simple.controller.jobs;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.*;
import java.util.Date;
@Component
public class HelloJob {
public final static long ONE_Minute = 60 * 1000;
public final static DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 每一分鐘執(zhí)行一次,需要在業(yè)務(wù)執(zhí)行完之后重新計(jì)時(shí)
*/
@Scheduled(fixedDelay = ONE_Minute)
public void fixedDelayJob(){
System.out.println(format.format(new Date())+" >>fixedDelay執(zhí)行....");
}
/**
* 每一分鐘執(zhí)行一次,無論上次任務(wù)是否執(zhí)行完
*/
@Scheduled(fixedRate = ONE_Minute)
public void fixedRateJob(){
System.out.println(format.format(new Date())+" >>fixedRate執(zhí)行....");
}
/**
* 每天3點(diǎn)15執(zhí)行一次
*/
@Scheduled(cron="0 15 3 * * ?")
public void cronJob(){
System.out.println(format.format(new Date())+" >>cron執(zhí)行....");
}
}
3.啟動(dòng)springboot,得到輸出結(jié)果
2019-01-22 12:09:00 >>fixedRate執(zhí)行....
2019-01-22 12:09:00 >>fixedDelay執(zhí)行....
2019-01-22 12:10:00 >>fixedRate執(zhí)行....
2019-01-22 12:10:00 >>fixedDelay執(zhí)行....
2019-01-22 12:11:00 >>fixedRate執(zhí)行....
2019-01-22 12:11:00 >>fixedDelay執(zhí)行....
2019-01-22 12:12:00 >>fixedRate執(zhí)行....
2019-01-22 12:12:00 >>fixedDelay執(zhí)行....
corn表達(dá)式
* 第一位,表示秒,取值0-59
* 第二位,表示分,取值0-59
* 第三位,表示小時(shí),取值0-23
* 第四位,日期天/日,取值1-31
* 第五位,日期月份,取值1-12
* 第六位,星期,取值1-7,星期一,星期二...,注:不是第1周,第二周的意思
另外:1表示星期天,2表示星期一。
* 第7為,年份,可以留空,取值1970-2099
(*)星號(hào):可以理解為每的意思,每秒,每分,每天,每月,每年...
(?)問號(hào):?jiǎn)柼?hào)只能出現(xiàn)在日期和星期這兩個(gè)位置,表示這個(gè)位置的值不確定,每天3點(diǎn)執(zhí)行,所以第六位星期的位置,我們是不需要關(guān)注的,就是不確定的值。同時(shí):日期和星期是兩個(gè)相互排斥的元素,通過問號(hào)來表明不指定值。比如,1月10日,比如是星期1,如果在星期的位置是另指定星期二,就前后沖突矛盾了。
(-)減號(hào):表達(dá)一個(gè)范圍,如在小時(shí)字段中使用“10-12”,則表示從10到12點(diǎn),即10,11,12
(,)逗號(hào):表達(dá)一個(gè)列表值,如在星期字段中使用“1,2,4”,則表示星期一,星期二,星期四
0 0 3 * * ? 每天3點(diǎn)執(zhí)行
0 5 3 * * ? 每天3點(diǎn)5分執(zhí)行
0 5 3 ? * * 每天3點(diǎn)5分執(zhí)行,與上面作用相同
0 5/10 3 * * ? 每天3點(diǎn)的 5分,15分,25分,35分,45分,55分這幾個(gè)時(shí)間點(diǎn)執(zhí)行
0 10 3 ? * 1 每周星期天,3點(diǎn)10分 執(zhí)行,注:1表示星期天
0 10 3 ? * 1#3 每個(gè)月的第三個(gè)星期,星期天 執(zhí)行,#號(hào)只能出現(xiàn)在星期的位置