在項目當中有時候需要定時去執行某個操作,這時候我們就需要時候到定時任務,我們這裏來簡單講解一下Springboot2.0.0定時任務。
注意,Springboot2.0.0和Springboot1版本配置Quartz有所不同。由於Springboot2.0.0在spring-boot-starter中已經包含了quart的依賴,所以我們一般項目搭建好之後不需要專門去配置Quartz,而Springboot2.0.0之前的版本還需要我們這邊手動去配置Quartz。我們這裏主要講解Springboot2.0.0版本,所以不對之前版本配置作講解。
當Springboot項目搭建完成之後,我們其實這是已經集成了Quartz,只需要在啓動類上添加定時任務的註解@EnableScheduling即可。
@SpringBootApplication
@EnableScheduling
public class CmfApplication {
public static void main(String[] args) {
SpringApplication.run(CmfApplication.class, args);
System.out.println("SpringBoot啓動成功!");
}
}
在啓動類中加入註解之後就能使用定時任務了,如下代碼是一個定時任務類,一定要記得在類上加上 @Component,這樣我們的Springboot才能掃描到這個類。同時在方法上加上@Scheduled註解,在註解中設置定時任務的頻率,這裏有兩種設置定時任務頻率的方式,下面代碼是兩種設置五秒執行一次任務的方法。
@Component
public class SchedulerTest {
//沒5秒執行一次
@Scheduled(fixedRate = 5000)
public void test() {
System.out.println("定時任務測試1:"+(new Date()));
}
//每隔6秒執行一次
@Scheduled(cron="*/5 * * * * ?")
public void test001() {
System.out.println("定時任務測試2:"+(new Date()));
}
}
@Scheduled中參數含義
fixedRate = 5000:上一次執行時間點之後5秒再次執行定時任務
fixedDelay = 5000 : 上一次任務執行完畢之後5秒再次執行任務
initialDelay=1000 : 第一次任務延後1秒執行,這個屬性可以和fixedRate以及fixedDelay聯合使用,例:@Scheduled(initialDelay=1000, fixedRate=5000)表示第一次任務延後1秒執行,然後每隔6秒鐘執行一次任務
cron表示每隔多少時間執行一次任務,這個時間可以自己靈活設定,從前到後依次是秒、分、小時、日、星期、月、年。