Java后端避坑——Quartz定时任务之重复间隔

2,918 阅读1分钟

Quartz 是一个完全由java编写的开源作业调度框架,在Spring + SpringMVC 或者Spring Boot环境中,我们都可以用它来实现定时任务策略。

当需要在规定的时间执行一次或在规定的时间段以一定的时间间隔重复触发执行Job时,SimpleTrigger 就可以满足要求,其中重复次数RepeatCount 和重复间隔RepeatInterval 是比较重要的两个属性。

我们可以根据业务需要设置对应的重复次数和重复间隔,也可以将重复次数和重复间隔都设置为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.

注:运行环境为 IntelliJ IDEA 2018.1.1

错误分析

Invocation of init method failed; nested exception is org.quartz.SchedulerException: Repeat Interval cannot be zero. (该语句的意思是:调用init方法失败,在嵌套SchedulerException的时候:重复间隔不能为零)

代码示例

 @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会简单很多!

积少成多,滴水穿石!