前言
大家应该都有所体会,使用Spring的任务调度给我们的开发带来了极大的便利,不过当我们的任务调度配置完成后,很难再对其进行更改,除非停止服务器,修改配置,然后再重启,显然这样是不利于线上操作的,为了实现动态的任务调度修改,我在网上也查阅了一些资料,大部分都是基于quartz实现的,使用Spring内置的任务调度则少之又少,而且效果不理想,需要在下次任务执行后,新的配置才能生效,做不到立即生效。本着探索研究的原则,查看了一下Spring的源码,下面为大家提供一种Spring内置任务调度实现添加、取消、重置的方法。话不多说了,来一起看看详细的介绍 吧。
实现方法如下
首先,我们需要启用Spring的任务调度
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
这一部分配置在网上是很常见的,接下来我们需要联合使用@EnableScheduling与org.springframework.scheduling.annotation.SchedulingConfigurer便携我们自己的调度配置,在SchedulingConfigurer接口中,需要实现一个void configureTasks(ScheduledTaskRegistrar taskRegistrar);方法,传统做法是在该方法中添加需要执行的调度信息。网上的基本撒谎那个也都是使用该方法实现的,使用addTriggerTask添加任务,并结合cron表达式动态修改调度时间,这里我们并不这样做。
查看一下ScheduledTaskRegistrar源码,我们发现该对象初始化完成后会执行scheduleTasks()方法,在该方法中添加任务调度信息,最终所有的任务信息都存放在名为scheduledFutures的集合中。
protected void scheduleTasks() {
long now = System.currentTimeMillis();
if (this.taskScheduler == null) {
this.localExecutor = Executors.newSingleThreadScheduledExecutor();
this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
}
if (this.triggerTasks != null) {
for (TriggerTask task : this.triggerTasks) {
this.scheduledFutures.add(this.taskScheduler.schedule(
task.getRunnable(), task.getTrigger()));
}
}
if (this.cronTasks != null) {
for (CronTask task : this.cronTasks) {
this.scheduledFutures.add(this.taskScheduler.schedule(
task.getRunnable(), task.getTrigger()));
}
}
if (this.fixedRateTasks != null) {
for (IntervalTask task : this.fixedRateTasks) {
if (task.getInitialDelay() > 0) {
Date startTime = new Date(now + task.getInitialDelay());
this.scheduledFutures.add(this.taskScheduler.scheduleAtFixedRate(
task.getRunnable(), startTime, task.getInterval()));
}
else {
this.scheduledFutures.add(this.taskScheduler.scheduleAtFixedRate(
task.getRunnable(), task.getInterval()));
}
}
}
if (