Support initial delay attribute for scheduled tasks
java.util.concurrent's ScheduledExecutorService and its #schedule* methods allow for an 'initialDelay' parameter in milliseconds. Similarly, Spring's TaskExecutor abstraction allows for a concrete 'startTime' expressed as a Date. However, Spring's <task:scheduled> XML element and @Scheduled annotation have, to date, not allowed for an initial delay parameter that can be propagated down to the underlying TaskScheduler/ScheduledExecutorService. This commit introduces initial-delay and #initialDelay attributes to task:scheduled and @Scheduled respectively, both indicating the number of milliseconds to wait before the first invocation of the method in question. Specifying a delay in this fashion is only valid in conjunction with fixed-rate and fixed-delay tasks (i.e. not with cron or trigger tasks). The principal changes required to support these new attributes lie in ScheduledTaskRegistrar, which previously supported registration of tasks in the form of a Runnable and a Long parameter indicating (in the case of fixed-rate and fixed-delay tasks), the interval with which the task should be executed. In order to accommodate a third (and optional) 'initialDelay' parameter, the IntervalTask class has been added as a holder for the Runnable to be executed, the interval in which to run it, and the optional initial delay. For symmetry, a TriggerTask and CronTask have also been added, the latter subclassing the former. And a 'Task' class has been added as a common ancestor for all the above. One oddity of the implementation is in the naming of the new setters in ScheduledTaskRegistrar. Prior to this commit, the setters were named #setFixedDelayTasks, #setFixedRateTasks, etc, each accepting a Map<Runnable, long>. In adding new setters for each task type, each accepting a List<IntervalTask>, List<CronTask> etc, naturally the approach would be to use method overloading and to introduce methods of the same name but with differing parameter types. Unfortunately however, Spring does not support injection against overloaded methods (due to fundamental limitations of the underlying JDK Introspector). This is not a problem when working with the ScheduledTaskRegistrar directly, e.g. from within a @Configuration class that implements SchedulingConfigurer, but is a problem from the point of view of the ScheduledTasksBeanDefinitionParser which parses the <task:scheduled> element - here the ScheduledTaskRegistrar is treated as a Spring bean and is thus subject to these limitations. The solution to this problem was simply to avoid overloading altogether, thus the naming of the new methods ending in "List", e.g. #setFixedDelayTasksList, etc. These methods exist primarily for use by the BeanDefinitionParser and are not really intended for use by application developers. The Javadoc for each of the new methods makes note of this. Issue: SPR-7022
This commit is contained in:
@@ -37,6 +37,7 @@ import java.lang.annotation.Target;
|
||||
*
|
||||
* @author Mark Fisher
|
||||
* @author Dave Syer
|
||||
* @author Chris Beams
|
||||
* @since 3.0
|
||||
* @see EnableScheduling
|
||||
* @see ScheduledAnnotationBeanPostProcessor
|
||||
@@ -69,4 +70,12 @@ public @interface Scheduled {
|
||||
*/
|
||||
long fixedRate() default -1;
|
||||
|
||||
/**
|
||||
* Number of milliseconds to delay before the first execution of a
|
||||
* {@link #fixedRate()} or {@link #fixedDelay()} task.
|
||||
* @return the initial delay in milliseconds
|
||||
* @since 3.2
|
||||
*/
|
||||
long initialDelay() default 0;
|
||||
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.scheduling.Trigger;
|
||||
import org.springframework.scheduling.config.CronTask;
|
||||
import org.springframework.scheduling.config.IntervalTask;
|
||||
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
|
||||
import org.springframework.scheduling.support.ScheduledMethodRunnable;
|
||||
import org.springframework.util.Assert;
|
||||
@@ -75,13 +77,7 @@ public class ScheduledAnnotationBeanPostProcessor
|
||||
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
private ScheduledTaskRegistrar registrar;
|
||||
|
||||
private final Map<Runnable, String> cronTasks = new HashMap<Runnable, String>();
|
||||
|
||||
private final Map<Runnable, Long> fixedDelayTasks = new HashMap<Runnable, Long>();
|
||||
|
||||
private final Map<Runnable, Long> fixedRateTasks = new HashMap<Runnable, Long>();
|
||||
private final ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar();
|
||||
|
||||
|
||||
/**
|
||||
@@ -146,19 +142,20 @@ public class ScheduledAnnotationBeanPostProcessor
|
||||
if (embeddedValueResolver != null) {
|
||||
cron = embeddedValueResolver.resolveStringValue(cron);
|
||||
}
|
||||
cronTasks.put(runnable, cron);
|
||||
registrar.addCronTask(new CronTask(runnable, cron));
|
||||
}
|
||||
long initialDelay = annotation.initialDelay();
|
||||
long fixedDelay = annotation.fixedDelay();
|
||||
if (fixedDelay >= 0) {
|
||||
Assert.isTrue(!processedSchedule, errorMessage);
|
||||
processedSchedule = true;
|
||||
fixedDelayTasks.put(runnable, fixedDelay);
|
||||
registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay));
|
||||
}
|
||||
long fixedRate = annotation.fixedRate();
|
||||
if (fixedRate >= 0) {
|
||||
Assert.isTrue(!processedSchedule, errorMessage);
|
||||
processedSchedule = true;
|
||||
fixedRateTasks.put(runnable, fixedRate);
|
||||
registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay));
|
||||
}
|
||||
Assert.isTrue(processedSchedule, errorMessage);
|
||||
}
|
||||
@@ -175,16 +172,6 @@ public class ScheduledAnnotationBeanPostProcessor
|
||||
Map<String, SchedulingConfigurer> configurers =
|
||||
this.applicationContext.getBeansOfType(SchedulingConfigurer.class);
|
||||
|
||||
if (this.cronTasks.isEmpty() && this.fixedDelayTasks.isEmpty() &&
|
||||
this.fixedRateTasks.isEmpty() && configurers.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.registrar = new ScheduledTaskRegistrar();
|
||||
this.registrar.setCronTasks(this.cronTasks);
|
||||
this.registrar.setFixedDelayTasks(this.fixedDelayTasks);
|
||||
this.registrar.setFixedRateTasks(this.fixedRateTasks);
|
||||
|
||||
if (this.scheduler != null) {
|
||||
this.registrar.setScheduler(this.scheduler);
|
||||
}
|
||||
@@ -193,7 +180,7 @@ public class ScheduledAnnotationBeanPostProcessor
|
||||
configurer.configureTasks(this.registrar);
|
||||
}
|
||||
|
||||
if (this.registrar.getScheduler() == null) {
|
||||
if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {
|
||||
Map<String, ? super Object> schedulers = new HashMap<String, Object>();
|
||||
schedulers.putAll(applicationContext.getBeansOfType(TaskScheduler.class));
|
||||
schedulers.putAll(applicationContext.getBeansOfType(ScheduledExecutorService.class));
|
||||
|
||||
@@ -38,6 +38,12 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
|
||||
*/
|
||||
public interface SchedulingConfigurer {
|
||||
|
||||
/**
|
||||
* Callback allowing a {@link org.springframework.scheduling.TaskScheduler
|
||||
* TaskScheduler} and specific {@link org.springframework.scheduling.config.Task Task}
|
||||
* instances to be registered against the given the {@link ScheduledTaskRegistrar}
|
||||
* @param taskRegistrar the registrar to be configured.
|
||||
*/
|
||||
void configureTasks(ScheduledTaskRegistrar taskRegistrar);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.scheduling.config;
|
||||
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.scheduling.support.CronTrigger;
|
||||
|
||||
/**
|
||||
* {@link TriggerTask} implementation defining a {@code Runnable} to be executed according
|
||||
* to a {@linkplain org.springframework.scheduling.support.CronSequenceGenerator standard
|
||||
* cron expression}.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @since 3.2
|
||||
* @see Scheduled#cron()
|
||||
* @see ScheduledTaskRegistrar#setCronTasksList(java.util.List)
|
||||
* @see org.springframework.scheduling.TaskScheduler
|
||||
*/
|
||||
public class CronTask extends TriggerTask {
|
||||
|
||||
private String expression;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new {@code CronTask}.
|
||||
* @param runnable the underlying task to execute
|
||||
* @param expression cron expression defining when the task should be executed
|
||||
*/
|
||||
public CronTask(Runnable runnable, String expression) {
|
||||
this(runnable, new CronTrigger(expression));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@code CronTask}.
|
||||
* @param runnable the underlying task to execute
|
||||
* @param cronTrigger the cron trigger defining when the task should be executed
|
||||
*/
|
||||
public CronTask(Runnable runnable, CronTrigger cronTrigger) {
|
||||
super(runnable, cronTrigger);
|
||||
this.expression = cronTrigger.getExpression();
|
||||
}
|
||||
|
||||
public String getExpression() {
|
||||
return expression;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.scheduling.config;
|
||||
|
||||
/**
|
||||
* {@link Task} implementation defining a {@code Runnable} to be executed at a given
|
||||
* millisecond interval which may be treated as fixed-rate or fixed-delay depending on
|
||||
* context.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @since 3.2
|
||||
* @see org.springframework.scheduling.annotation.Scheduled#fixedRate()
|
||||
* @see org.springframework.scheduling.annotation.Scheduled#fixedDelay()
|
||||
* @see ScheduledTaskRegistrar#setFixedRateTasksList(java.util.List)
|
||||
* @see ScheduledTaskRegistrar#setFixedDelayTasksList(java.util.List)
|
||||
* @see org.springframework.scheduling.TaskScheduler
|
||||
*/
|
||||
public class IntervalTask extends Task {
|
||||
|
||||
private final long interval;
|
||||
|
||||
private final long initialDelay;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new {@code IntervalTask}.
|
||||
* @param runnable the underlying task to execute
|
||||
* @param interval how often in milliseconds the task should be executed
|
||||
* @param initialDelay initial delay before first execution of the task
|
||||
*/
|
||||
public IntervalTask(Runnable runnable, long interval, long initialDelay) {
|
||||
super(runnable);
|
||||
this.initialDelay = initialDelay;
|
||||
this.interval = interval;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@code IntervalTask} with no initial delay.
|
||||
* @param runnable the underlying task to execute
|
||||
* @param interval how often in milliseconds the task should be executed
|
||||
*/
|
||||
public IntervalTask(Runnable runnable, long interval) {
|
||||
this(runnable, interval, 0);
|
||||
}
|
||||
|
||||
|
||||
public long getInterval() {
|
||||
return interval;
|
||||
}
|
||||
|
||||
public long getInitialDelay() {
|
||||
return initialDelay;
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,10 @@
|
||||
|
||||
package org.springframework.scheduling.config;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -33,8 +35,8 @@ import org.springframework.scheduling.support.CronTrigger;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Helper bean for registering tasks with a {@link TaskScheduler},
|
||||
* typically using cron expressions.
|
||||
* Helper bean for registering tasks with a {@link TaskScheduler}, typically using cron
|
||||
* expressions.
|
||||
*
|
||||
* <p>As of Spring 3.1, {@code ScheduledTaskRegistrar} has a more prominent user-facing
|
||||
* role when used in conjunction with the @{@link
|
||||
@@ -43,6 +45,7 @@ import org.springframework.util.Assert;
|
||||
* SchedulingConfigurer} callback interface.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
* @since 3.0
|
||||
* @see org.springframework.scheduling.annotation.EnableAsync
|
||||
* @see org.springframework.scheduling.annotation.SchedulingConfigurer
|
||||
@@ -53,13 +56,13 @@ public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean
|
||||
|
||||
private ScheduledExecutorService localExecutor;
|
||||
|
||||
private Map<Runnable, Trigger> triggerTasks;
|
||||
private List<TriggerTask> triggerTasks;
|
||||
|
||||
private Map<Runnable, String> cronTasks;
|
||||
private List<CronTask> cronTasks;
|
||||
|
||||
private Map<Runnable, Long> fixedRateTasks;
|
||||
private List<IntervalTask> fixedRateTasks;
|
||||
|
||||
private Map<Runnable, Long> fixedDelayTasks;
|
||||
private List<IntervalTask> fixedDelayTasks;
|
||||
|
||||
private final Set<ScheduledFuture<?>> scheduledFutures = new LinkedHashSet<ScheduledFuture<?>>();
|
||||
|
||||
@@ -97,11 +100,25 @@ public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean
|
||||
return this.taskScheduler;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Specify triggered tasks as a Map of Runnables (the tasks) and Trigger objects
|
||||
* (typically custom implementations of the {@link Trigger} interface).
|
||||
*/
|
||||
public void setTriggerTasks(Map<Runnable, Trigger> triggerTasks) {
|
||||
this.triggerTasks = new ArrayList<TriggerTask>();
|
||||
for (Map.Entry<Runnable, Trigger> task : triggerTasks.entrySet()) {
|
||||
this.triggerTasks.add(new TriggerTask(task.getKey(), task.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify triggered tasks as a list of {@link TriggerTask} objects. Primarily used
|
||||
* by {@code <task:*>} namespace parsing.
|
||||
* @since 3.2
|
||||
* @see ScheduledTasksBeanDefinitionParser
|
||||
*/
|
||||
public void setTriggerTasksList(List<TriggerTask> triggerTasks) {
|
||||
this.triggerTasks = triggerTasks;
|
||||
}
|
||||
|
||||
@@ -110,6 +127,19 @@ public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean
|
||||
* @see CronTrigger
|
||||
*/
|
||||
public void setCronTasks(Map<Runnable, String> cronTasks) {
|
||||
this.cronTasks = new ArrayList<CronTask>();
|
||||
for (Map.Entry<Runnable, String> task : cronTasks.entrySet()) {
|
||||
this.addCronTask(task.getKey(), task.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify triggered tasks as a list of {@link CronTask} objects. Primarily used by
|
||||
* {@code <task:*>} namespace parsing.
|
||||
* @since 3.2
|
||||
* @see ScheduledTasksBeanDefinitionParser
|
||||
*/
|
||||
public void setCronTasksList(List<CronTask> cronTasks) {
|
||||
this.cronTasks = cronTasks;
|
||||
}
|
||||
|
||||
@@ -118,6 +148,19 @@ public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean
|
||||
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
|
||||
*/
|
||||
public void setFixedRateTasks(Map<Runnable, Long> fixedRateTasks) {
|
||||
this.fixedRateTasks = new ArrayList<IntervalTask>();
|
||||
for (Map.Entry<Runnable, Long> task : fixedRateTasks.entrySet()) {
|
||||
this.addFixedRateTask(task.getKey(), task.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify fixed-rate tasks as a list of {@link IntervalTask} objects. Primarily used
|
||||
* by {@code <task:*>} namespace parsing.
|
||||
* @since 3.2
|
||||
* @see ScheduledTasksBeanDefinitionParser
|
||||
*/
|
||||
public void setFixedRateTasksList(List<IntervalTask> fixedRateTasks) {
|
||||
this.fixedRateTasks = fixedRateTasks;
|
||||
}
|
||||
|
||||
@@ -126,6 +169,19 @@ public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean
|
||||
* @see TaskScheduler#scheduleWithFixedDelay(Runnable, long)
|
||||
*/
|
||||
public void setFixedDelayTasks(Map<Runnable, Long> fixedDelayTasks) {
|
||||
this.fixedDelayTasks = new ArrayList<IntervalTask>();
|
||||
for (Map.Entry<Runnable, Long> task : fixedDelayTasks.entrySet()) {
|
||||
this.addFixedDelayTask(task.getKey(), task.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify fixed-delay tasks as a list of {@link IntervalTask} objects. Primarily used
|
||||
* by {@code <task:*>} namespace parsing.
|
||||
* @since 3.2
|
||||
* @see ScheduledTasksBeanDefinitionParser
|
||||
*/
|
||||
public void setFixedDelayTasksList(List<IntervalTask> fixedDelayTasks) {
|
||||
this.fixedDelayTasks = fixedDelayTasks;
|
||||
}
|
||||
|
||||
@@ -134,20 +190,37 @@ public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean
|
||||
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
|
||||
*/
|
||||
public void addTriggerTask(Runnable task, Trigger trigger) {
|
||||
this.addTriggerTask(new TriggerTask(task, trigger));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a {@code TriggerTask}.
|
||||
* @since 3.2
|
||||
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
|
||||
*/
|
||||
public void addTriggerTask(TriggerTask task) {
|
||||
if (this.triggerTasks == null) {
|
||||
this.triggerTasks = new HashMap<Runnable, Trigger>();
|
||||
this.triggerTasks = new ArrayList<TriggerTask>();
|
||||
}
|
||||
this.triggerTasks.put(task, trigger);
|
||||
this.triggerTasks.add(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a Runnable task to be triggered per the given cron expression
|
||||
*/
|
||||
public void addCronTask(Runnable task, String cronExpression) {
|
||||
public void addCronTask(Runnable task, String expression) {
|
||||
this.addCronTask(new CronTask(task, expression));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a {@link CronTask}.
|
||||
* @since 3.2
|
||||
*/
|
||||
public void addCronTask(CronTask task) {
|
||||
if (this.cronTasks == null) {
|
||||
this.cronTasks = new HashMap<Runnable, String>();
|
||||
this.cronTasks = new ArrayList<CronTask>();
|
||||
}
|
||||
this.cronTasks.put(task, cronExpression);
|
||||
this.cronTasks.add(task);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -155,10 +228,19 @@ public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean
|
||||
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
|
||||
*/
|
||||
public void addFixedRateTask(Runnable task, long period) {
|
||||
this.addFixedRateTask(new IntervalTask(task, period, 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a fixed-rate {@link IntervalTask}.
|
||||
* @since 3.2
|
||||
* @see TaskScheduler#scheduleAtFixedRate(Runnable, long)
|
||||
*/
|
||||
public void addFixedRateTask(IntervalTask task) {
|
||||
if (this.fixedRateTasks == null) {
|
||||
this.fixedRateTasks = new HashMap<Runnable, Long>();
|
||||
this.fixedRateTasks = new ArrayList<IntervalTask>();
|
||||
}
|
||||
this.fixedRateTasks.put(task, period);
|
||||
this.fixedRateTasks.add(task);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -166,10 +248,30 @@ public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean
|
||||
* @see TaskScheduler#scheduleWithFixedDelay(Runnable, long)
|
||||
*/
|
||||
public void addFixedDelayTask(Runnable task, long delay) {
|
||||
this.addFixedDelayTask(new IntervalTask(task, delay, 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a fixed-delay {@link IntervalTask}.
|
||||
* @since 3.2
|
||||
* @see TaskScheduler#scheduleWithFixedDelay(Runnable, long)
|
||||
*/
|
||||
public void addFixedDelayTask(IntervalTask task) {
|
||||
if (this.fixedDelayTasks == null) {
|
||||
this.fixedDelayTasks = new HashMap<Runnable, Long>();
|
||||
this.fixedDelayTasks = new ArrayList<IntervalTask>();
|
||||
}
|
||||
this.fixedDelayTasks.put(task, delay);
|
||||
this.fixedDelayTasks.add(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether this {@code ScheduledTaskRegistrar} has any tasks registered.
|
||||
* @since 3.2
|
||||
*/
|
||||
public boolean hasTasks() {
|
||||
return (this.fixedRateTasks != null && !this.fixedRateTasks.isEmpty()) ||
|
||||
(this.fixedDelayTasks != null && !this.fixedDelayTasks.isEmpty()) ||
|
||||
(this.cronTasks != null && !this.cronTasks.isEmpty()) ||
|
||||
(this.triggerTasks != null && !this.triggerTasks.isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -177,28 +279,48 @@ public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean
|
||||
* #setTaskScheduler(TaskScheduler) task scheduler.
|
||||
*/
|
||||
public void afterPropertiesSet() {
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
if (this.taskScheduler == null) {
|
||||
this.localExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
|
||||
}
|
||||
if (this.triggerTasks != null) {
|
||||
for (Map.Entry<Runnable, Trigger> entry : this.triggerTasks.entrySet()) {
|
||||
this.scheduledFutures.add(this.taskScheduler.schedule(entry.getKey(), entry.getValue()));
|
||||
for (TriggerTask task : triggerTasks) {
|
||||
this.scheduledFutures.add(this.taskScheduler.schedule(
|
||||
task.getRunnable(), task.getTrigger()));
|
||||
}
|
||||
}
|
||||
if (this.cronTasks != null) {
|
||||
for (Map.Entry<Runnable, String> entry : this.cronTasks.entrySet()) {
|
||||
this.scheduledFutures.add(this.taskScheduler.schedule(entry.getKey(), new CronTrigger(entry.getValue())));
|
||||
for (CronTask task : cronTasks) {
|
||||
this.scheduledFutures.add(this.taskScheduler.schedule(
|
||||
task.getRunnable(), task.getTrigger()));
|
||||
}
|
||||
}
|
||||
if (this.fixedRateTasks != null) {
|
||||
for (Map.Entry<Runnable, Long> entry : this.fixedRateTasks.entrySet()) {
|
||||
this.scheduledFutures.add(this.taskScheduler.scheduleAtFixedRate(entry.getKey(), entry.getValue()));
|
||||
for (IntervalTask task : 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 (this.fixedDelayTasks != null) {
|
||||
for (Map.Entry<Runnable, Long> entry : this.fixedDelayTasks.entrySet()) {
|
||||
this.scheduledFutures.add(this.taskScheduler.scheduleWithFixedDelay(entry.getKey(), entry.getValue()));
|
||||
for (IntervalTask task : fixedDelayTasks) {
|
||||
if (task.getInitialDelay() > 0) {
|
||||
Date startTime = new Date(now + task.getInitialDelay());
|
||||
this.scheduledFutures.add(this.taskScheduler.scheduleWithFixedDelay(
|
||||
task.getRunnable(), startTime, task.getInterval()));
|
||||
}
|
||||
else {
|
||||
this.scheduledFutures.add(this.taskScheduler.scheduleWithFixedDelay(
|
||||
task.getRunnable(), task.getInterval()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ package org.springframework.scheduling.config;
|
||||
import org.springframework.beans.factory.config.RuntimeBeanReference;
|
||||
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.beans.factory.support.ManagedMap;
|
||||
import org.springframework.beans.factory.support.ManagedList;
|
||||
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
|
||||
import org.springframework.beans.factory.xml.ParserContext;
|
||||
import org.springframework.util.StringUtils;
|
||||
@@ -32,11 +32,13 @@ import org.w3c.dom.NodeList;
|
||||
* Parser for the 'scheduled-tasks' element of the scheduling namespace.
|
||||
*
|
||||
* @author Mark Fisher
|
||||
* @author Chris Beams
|
||||
* @since 3.0
|
||||
*/
|
||||
public class ScheduledTasksBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
|
||||
|
||||
private static final String ELEMENT_SCHEDULED = "scheduled";
|
||||
private static final long ZERO_INITIAL_DELAY = 0;
|
||||
|
||||
@Override
|
||||
protected boolean shouldGenerateId() {
|
||||
@@ -51,10 +53,10 @@ public class ScheduledTasksBeanDefinitionParser extends AbstractSingleBeanDefini
|
||||
@Override
|
||||
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
|
||||
builder.setLazyInit(false); // lazy scheduled tasks are a contradiction in terms -> force to false
|
||||
ManagedMap<RuntimeBeanReference, String> cronTaskMap = new ManagedMap<RuntimeBeanReference, String>();
|
||||
ManagedMap<RuntimeBeanReference, String> fixedDelayTaskMap = new ManagedMap<RuntimeBeanReference, String>();
|
||||
ManagedMap<RuntimeBeanReference, String> fixedRateTaskMap = new ManagedMap<RuntimeBeanReference, String>();
|
||||
ManagedMap<RuntimeBeanReference, RuntimeBeanReference> triggerTaskMap = new ManagedMap<RuntimeBeanReference, RuntimeBeanReference>();
|
||||
ManagedList<RuntimeBeanReference> cronTaskList = new ManagedList<RuntimeBeanReference>();
|
||||
ManagedList<RuntimeBeanReference> fixedDelayTaskList = new ManagedList<RuntimeBeanReference>();
|
||||
ManagedList<RuntimeBeanReference> fixedRateTaskList = new ManagedList<RuntimeBeanReference>();
|
||||
ManagedList<RuntimeBeanReference> triggerTaskList = new ManagedList<RuntimeBeanReference>();
|
||||
NodeList childNodes = element.getChildNodes();
|
||||
for (int i = 0; i < childNodes.getLength(); i++) {
|
||||
Node child = childNodes.item(i);
|
||||
@@ -64,54 +66,67 @@ public class ScheduledTasksBeanDefinitionParser extends AbstractSingleBeanDefini
|
||||
Element taskElement = (Element) child;
|
||||
String ref = taskElement.getAttribute("ref");
|
||||
String method = taskElement.getAttribute("method");
|
||||
|
||||
|
||||
// Check that 'ref' and 'method' are specified
|
||||
if (!StringUtils.hasText(ref) || !StringUtils.hasText(method)) {
|
||||
parserContext.getReaderContext().error("Both 'ref' and 'method' are required", taskElement);
|
||||
// Continue with the possible next task element
|
||||
continue;
|
||||
}
|
||||
|
||||
RuntimeBeanReference runnableBeanRef = new RuntimeBeanReference(
|
||||
createRunnableBean(ref, method, taskElement, parserContext));
|
||||
|
||||
String cronAttribute = taskElement.getAttribute("cron");
|
||||
String fixedDelayAttribute = taskElement.getAttribute("fixed-delay");
|
||||
String fixedRateAttribute = taskElement.getAttribute("fixed-rate");
|
||||
String triggerAttribute = taskElement.getAttribute("trigger");
|
||||
String initialDelayAttribute = taskElement.getAttribute("initial-delay");
|
||||
|
||||
boolean hasCronAttribute = StringUtils.hasText(cronAttribute);
|
||||
boolean hasFixedDelayAttribute = StringUtils.hasText(fixedDelayAttribute);
|
||||
boolean hasFixedRateAttribute = StringUtils.hasText(fixedRateAttribute);
|
||||
boolean hasTriggerAttribute = StringUtils.hasText(triggerAttribute);
|
||||
boolean hasInitialDelayAttribute = StringUtils.hasText(initialDelayAttribute);
|
||||
|
||||
if (!(hasCronAttribute | hasFixedDelayAttribute | hasFixedRateAttribute | hasTriggerAttribute)) {
|
||||
if (!(hasCronAttribute || hasFixedDelayAttribute || hasFixedRateAttribute || hasTriggerAttribute)) {
|
||||
parserContext.getReaderContext().error(
|
||||
"one of the 'cron', 'fixed-delay', 'fixed-rate', or 'trigger' attributes is required", taskElement);
|
||||
continue; // with the possible next task element
|
||||
}
|
||||
|
||||
if (hasCronAttribute) {
|
||||
cronTaskMap.put(runnableBeanRef, cronAttribute);
|
||||
if (hasInitialDelayAttribute && (hasCronAttribute || hasTriggerAttribute)) {
|
||||
parserContext.getReaderContext().error(
|
||||
"the 'initial-delay' attribute may not be used with cron and trigger tasks", taskElement);
|
||||
continue; // with the possible next task element
|
||||
}
|
||||
|
||||
String runnableName =
|
||||
runnableReference(ref, method, taskElement, parserContext).getBeanName();
|
||||
|
||||
if (hasFixedDelayAttribute) {
|
||||
fixedDelayTaskMap.put(runnableBeanRef, fixedDelayAttribute);
|
||||
fixedDelayTaskList.add(intervalTaskReference(runnableName,
|
||||
initialDelayAttribute, fixedDelayAttribute, taskElement, parserContext));
|
||||
}
|
||||
if (hasFixedRateAttribute) {
|
||||
fixedRateTaskMap.put(runnableBeanRef, fixedRateAttribute);
|
||||
fixedRateTaskList.add(intervalTaskReference(runnableName,
|
||||
initialDelayAttribute, fixedRateAttribute, taskElement, parserContext));
|
||||
}
|
||||
if (hasCronAttribute) {
|
||||
cronTaskList.add(cronTaskReference(runnableName, cronAttribute,
|
||||
taskElement, parserContext));
|
||||
}
|
||||
if (hasTriggerAttribute) {
|
||||
triggerTaskMap.put(runnableBeanRef, new RuntimeBeanReference(triggerAttribute));
|
||||
String triggerName = new RuntimeBeanReference(triggerAttribute).getBeanName();
|
||||
triggerTaskList.add(triggerTaskReference(runnableName, triggerName,
|
||||
taskElement, parserContext));
|
||||
}
|
||||
}
|
||||
String schedulerRef = element.getAttribute("scheduler");
|
||||
if (StringUtils.hasText(schedulerRef)) {
|
||||
builder.addPropertyReference("taskScheduler", schedulerRef);
|
||||
}
|
||||
builder.addPropertyValue("cronTasks", cronTaskMap);
|
||||
builder.addPropertyValue("fixedDelayTasks", fixedDelayTaskMap);
|
||||
builder.addPropertyValue("fixedRateTasks", fixedRateTaskMap);
|
||||
builder.addPropertyValue("triggerTasks", triggerTaskMap);
|
||||
builder.addPropertyValue("cronTasksList", cronTaskList);
|
||||
builder.addPropertyValue("fixedDelayTasksList", fixedDelayTaskList);
|
||||
builder.addPropertyValue("fixedRateTasksList", fixedRateTaskList);
|
||||
builder.addPropertyValue("triggerTasksList", triggerTaskList);
|
||||
}
|
||||
|
||||
private boolean isScheduledElement(Node node, ParserContext parserContext) {
|
||||
@@ -119,16 +134,49 @@ public class ScheduledTasksBeanDefinitionParser extends AbstractSingleBeanDefini
|
||||
ELEMENT_SCHEDULED.equals(parserContext.getDelegate().getLocalName(node));
|
||||
}
|
||||
|
||||
private String createRunnableBean(String ref, String method, Element taskElement, ParserContext parserContext) {
|
||||
private RuntimeBeanReference runnableReference(String ref, String method, Element taskElement, ParserContext parserContext) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
|
||||
"org.springframework.scheduling.support.ScheduledMethodRunnable");
|
||||
builder.addConstructorArgReference(ref);
|
||||
builder.addConstructorArgValue(method);
|
||||
return beanReference(taskElement, parserContext, builder);
|
||||
}
|
||||
|
||||
private RuntimeBeanReference intervalTaskReference(String runnableBeanName,
|
||||
String initialDelay, String interval, Element taskElement, ParserContext parserContext) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
|
||||
"org.springframework.scheduling.config.IntervalTask");
|
||||
builder.addConstructorArgReference(runnableBeanName);
|
||||
builder.addConstructorArgValue(interval);
|
||||
builder.addConstructorArgValue(StringUtils.hasLength(initialDelay) ? initialDelay : ZERO_INITIAL_DELAY);
|
||||
return beanReference(taskElement, parserContext, builder);
|
||||
}
|
||||
|
||||
private RuntimeBeanReference cronTaskReference(String runnableBeanName,
|
||||
String cronExpression, Element taskElement, ParserContext parserContext) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
|
||||
"org.springframework.scheduling.config.CronTask");
|
||||
builder.addConstructorArgReference(runnableBeanName);
|
||||
builder.addConstructorArgValue(cronExpression);
|
||||
return beanReference(taskElement, parserContext, builder);
|
||||
}
|
||||
|
||||
private RuntimeBeanReference triggerTaskReference(String runnableBeanName,
|
||||
String triggerBeanName, Element taskElement, ParserContext parserContext) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
|
||||
"org.springframework.scheduling.config.TriggerTask");
|
||||
builder.addConstructorArgReference(runnableBeanName);
|
||||
builder.addConstructorArgReference(triggerBeanName);
|
||||
return beanReference(taskElement, parserContext, builder);
|
||||
}
|
||||
|
||||
private RuntimeBeanReference beanReference(Element taskElement,
|
||||
ParserContext parserContext, BeanDefinitionBuilder builder) {
|
||||
// Extract the source of the current task
|
||||
builder.getRawBeanDefinition().setSource(parserContext.extractSource(taskElement));
|
||||
String generatedName = parserContext.getReaderContext().generateBeanName(builder.getRawBeanDefinition());
|
||||
parserContext.registerBeanComponent(new BeanComponentDefinition(builder.getBeanDefinition(), generatedName));
|
||||
return generatedName;
|
||||
return new RuntimeBeanReference(generatedName);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.scheduling.config;
|
||||
|
||||
/**
|
||||
* Holder class defining a {@code Runnable} to be executed as a task, typically at a
|
||||
* scheduled time or interval. See subclass hierarchy for various scheduling approaches.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @since 3.2
|
||||
*/
|
||||
public class Task {
|
||||
|
||||
private final Runnable runnable;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new {@code Task}.
|
||||
* @param runnable the underlying task to execute.
|
||||
*/
|
||||
public Task(Runnable runnable) {
|
||||
this.runnable = runnable;
|
||||
}
|
||||
|
||||
|
||||
public Runnable getRunnable() {
|
||||
return runnable;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.scheduling.config;
|
||||
|
||||
import org.springframework.scheduling.Trigger;
|
||||
|
||||
/**
|
||||
* {@link Task} implementation defining a {@code Runnable} to be executed according to a
|
||||
* given {@link Trigger}.
|
||||
*
|
||||
* @author Chris Beams
|
||||
* @since 3.2
|
||||
* @see Trigger#nextExecutionTime(org.springframework.scheduling.TriggerContext)
|
||||
* @see ScheduledTaskRegistrar#setTriggerTasksList(java.util.List)
|
||||
* @see org.springframework.scheduling.TaskScheduler#schedule(Runnable, Trigger)
|
||||
*/
|
||||
public class TriggerTask extends Task {
|
||||
|
||||
private final Trigger trigger;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new {@link TriggerTask}.
|
||||
* @param runnable the underlying task to execute
|
||||
* @param trigger specifies when the task should be executed
|
||||
*/
|
||||
public TriggerTask(Runnable runnable, Trigger trigger) {
|
||||
super(runnable);
|
||||
this.trigger = trigger;
|
||||
}
|
||||
|
||||
|
||||
public Trigger getTrigger() {
|
||||
return trigger;
|
||||
}
|
||||
}
|
||||
@@ -339,6 +339,10 @@ public class CronSequenceGenerator {
|
||||
return result;
|
||||
}
|
||||
|
||||
String getExpression() {
|
||||
return this.expression;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof CronSequenceGenerator)) {
|
||||
|
||||
@@ -72,6 +72,9 @@ public class CronTrigger implements Trigger {
|
||||
return this.sequenceGenerator.next(date);
|
||||
}
|
||||
|
||||
public String getExpression() {
|
||||
return this.sequenceGenerator.getExpression();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
|
||||
Reference in New Issue
Block a user