Java後端避坑——Quartz定時任務之重複間隔

Quartz 是一個徹底由java編寫的開源做業調度框架,在Spring + SpringMVC 或者Spring Boot環境中,咱們均可以用它來實現定時任務策略。java

當須要在規定的時間執行一次或在規定的時間段以必定的時間間隔重複觸發執行Job時,SimpleTrigger 就能夠知足要求,其中重複次數RepeatCount 和重複間隔RepeatInterval 是比較重要的兩個屬性。spring

咱們能夠根據業務須要設置對應的重複次數和重複間隔,也能夠將重複次數和重複間隔都設置爲0,可是若是咱們單獨把重複間隔設置爲0,將會出現以下程序運行錯誤:框架

2019-04-15 20:51:31.948 WARN 9984 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'schedulerFactoryBean' defined in class path resource [com/chb/quartzdemo/QuartzConfig.class]: Invocation of init method failed; nested exception is org.quartz.SchedulerException: Repeat Interval cannot be zero.spa

注:運行環境爲 IntelliJ IDEA 2018.1.1

錯誤分析

Invocation of init method failed; nested exception is org.quartz.SchedulerException: Repeat Interval cannot be zero. (該語句的意思是:調用init方法失敗,在嵌套SchedulerException的時候:重複間隔不能爲零)code

代碼示例

@Bean
 SimpleTriggerFactoryBean simpleTriggerFactoryBean(){
	 SimpleTriggerFactoryBean bean =new SimpleTriggerFactoryBean();
     bean.setStartTime(new Date());
     bean.setRepeatCount(5);//重複的次數
     bean.setJobDetail(methodInvokingJobDetailFactoryBean().getObject());
        bean.setRepeatInterval(0);//重複間隔
        return bean;
    }
複製代碼

爲何重複間隔不能單獨設置爲0呢?

這是由於當咱們設置了重複次數以後,若是沒有了重複間隔的時間,系統就不知道要多久重複一次了,那麼也就無法實現定時任務的功能了。開發

雖然SimpleTrigger在開發中使用得比較少,不過它用起來相對於Cronrigger會簡單不少!

聚沙成塔,滴水穿石!get

相關文章
相關標籤/搜索