最近用到quartz做集群,需求每隔一段时间执行一次任务。
发现在配置较短的时间间隔,比如15秒钟执行一次时,会出现,服务器启动会有多个线程(不等,有时候2个,多的时候4个,quartz线程数目用的默认的10个)重复执行该任务。
控制台信息如下:
而当我配置成1min执行一次的时候,就没有问题,不会重发执行。
主要的配置文件如下,求解,感谢感谢。
<bean id="autoRepeatRequestTask"
class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass">
<value>com..job.AutoRequestRepeatJob</value>
</property>
<property name="durability" value="true" />
<property name="requestsRecovery" value="true" />
</bean>
<!-- 定义触发时间 -->
<bean id="autoRepeatRequestDoTime"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<ref bean="autoRepeatRequestTask" />
</property>
<!-- cron表达式 -->
<property name="cronExpression">
<value>0 * * * * ?</value>
<!--每分钟执行一次 -->
</property>
</bean>
<!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
<bean id="startQuartz" lazy-init="false" autowire="no"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
destroy-method="destroy">
<property name="configLocation" value="classpath:quartz.properties" />
<property name="triggers">
<list>
<ref bean="autoRepeatRequestDoTime" />
</list>
</property>
<property name="startupDelay" value="10" />
<property name="applicationContextSchedulerContextKey" value="applicationContextKey" />
</bean>
执行的任务类:
@PersistJobDataAfterExecution
@DisallowConcurrentExecution // 不允许并发执行
public class AutoRequestRepeatJob extends QuartzJobBean {
private static final Logger LOGGER = LoggerFactory.getLogger(AutoRequestRepeatJob.class);
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println(Thread.currentThread().getName()+"------初始化了"+DateTimeUtils.getNowHHmmss());
RequestRepeatService requestRepeatService = getApplicationContext(context).getBean(RequestRepeatService.class);
requestRepeatService.autoRepeatRequest();
}
private ApplicationContext getApplicationContext(final JobExecutionContext jobexecutioncontext) {
try {
return (ApplicationContext) jobexecutioncontext.getScheduler().getContext().get("applicationContextKey");
} catch (SchedulerException e) {
LOGGER.error("jobexecutioncontext.getScheduler().getContext() error!", e);
throw new RuntimeException(e);
}
}
}