Skip to content

Commit 53673d6

Browse files
committed
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
1 parent 4d5fe57 commit 53673d6

File tree

18 files changed

+659
-112
lines changed

18 files changed

+659
-112
lines changed

spring-context/src/main/java/org/springframework/scheduling/annotation/Scheduled.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
*
3838
* @author Mark Fisher
3939
* @author Dave Syer
40+
* @author Chris Beams
4041
* @since 3.0
4142
* @see EnableScheduling
4243
* @see ScheduledAnnotationBeanPostProcessor
@@ -69,4 +70,12 @@
6970
*/
7071
long fixedRate() default -1;
7172

73+
/**
74+
* Number of milliseconds to delay before the first execution of a
75+
* {@link #fixedRate()} or {@link #fixedDelay()} task.
76+
* @return the initial delay in milliseconds
77+
* @since 3.2
78+
*/
79+
long initialDelay() default 0;
80+
7281
}

spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
import org.springframework.core.annotation.AnnotationUtils;
3535
import org.springframework.scheduling.TaskScheduler;
3636
import org.springframework.scheduling.Trigger;
37+
import org.springframework.scheduling.config.CronTask;
38+
import org.springframework.scheduling.config.IntervalTask;
3739
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
3840
import org.springframework.scheduling.support.ScheduledMethodRunnable;
3941
import org.springframework.util.Assert;
@@ -75,13 +77,7 @@ public class ScheduledAnnotationBeanPostProcessor
7577

7678
private ApplicationContext applicationContext;
7779

78-
private ScheduledTaskRegistrar registrar;
79-
80-
private final Map<Runnable, String> cronTasks = new HashMap<Runnable, String>();
81-
82-
private final Map<Runnable, Long> fixedDelayTasks = new HashMap<Runnable, Long>();
83-
84-
private final Map<Runnable, Long> fixedRateTasks = new HashMap<Runnable, Long>();
80+
private final ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar();
8581

8682

8783
/**
@@ -146,19 +142,20 @@ public void doWith(Method method) throws IllegalArgumentException, IllegalAccess
146142
if (embeddedValueResolver != null) {
147143
cron = embeddedValueResolver.resolveStringValue(cron);
148144
}
149-
cronTasks.put(runnable, cron);
145+
registrar.addCronTask(new CronTask(runnable, cron));
150146
}
147+
long initialDelay = annotation.initialDelay();
151148
long fixedDelay = annotation.fixedDelay();
152149
if (fixedDelay >= 0) {
153150
Assert.isTrue(!processedSchedule, errorMessage);
154151
processedSchedule = true;
155-
fixedDelayTasks.put(runnable, fixedDelay);
152+
registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay));
156153
}
157154
long fixedRate = annotation.fixedRate();
158155
if (fixedRate >= 0) {
159156
Assert.isTrue(!processedSchedule, errorMessage);
160157
processedSchedule = true;
161-
fixedRateTasks.put(runnable, fixedRate);
158+
registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay));
162159
}
163160
Assert.isTrue(processedSchedule, errorMessage);
164161
}
@@ -175,16 +172,6 @@ public void onApplicationEvent(ContextRefreshedEvent event) {
175172
Map<String, SchedulingConfigurer> configurers =
176173
this.applicationContext.getBeansOfType(SchedulingConfigurer.class);
177174

178-
if (this.cronTasks.isEmpty() && this.fixedDelayTasks.isEmpty() &&
179-
this.fixedRateTasks.isEmpty() && configurers.isEmpty()) {
180-
return;
181-
}
182-
183-
this.registrar = new ScheduledTaskRegistrar();
184-
this.registrar.setCronTasks(this.cronTasks);
185-
this.registrar.setFixedDelayTasks(this.fixedDelayTasks);
186-
this.registrar.setFixedRateTasks(this.fixedRateTasks);
187-
188175
if (this.scheduler != null) {
189176
this.registrar.setScheduler(this.scheduler);
190177
}
@@ -193,7 +180,7 @@ public void onApplicationEvent(ContextRefreshedEvent event) {
193180
configurer.configureTasks(this.registrar);
194181
}
195182

196-
if (this.registrar.getScheduler() == null) {
183+
if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {
197184
Map<String, ? super Object> schedulers = new HashMap<String, Object>();
198185
schedulers.putAll(applicationContext.getBeansOfType(TaskScheduler.class));
199186
schedulers.putAll(applicationContext.getBeansOfType(ScheduledExecutorService.class));

spring-context/src/main/java/org/springframework/scheduling/annotation/SchedulingConfigurer.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@
3838
*/
3939
public interface SchedulingConfigurer {
4040

41+
/**
42+
* Callback allowing a {@link org.springframework.scheduling.TaskScheduler
43+
* TaskScheduler} and specific {@link org.springframework.scheduling.config.Task Task}
44+
* instances to be registered against the given the {@link ScheduledTaskRegistrar}
45+
* @param taskRegistrar the registrar to be configured.
46+
*/
4147
void configureTasks(ScheduledTaskRegistrar taskRegistrar);
4248

4349
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* Copyright 2002-2012 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.scheduling.config;
18+
19+
import org.springframework.scheduling.annotation.Scheduled;
20+
import org.springframework.scheduling.support.CronTrigger;
21+
22+
/**
23+
* {@link TriggerTask} implementation defining a {@code Runnable} to be executed according
24+
* to a {@linkplain org.springframework.scheduling.support.CronSequenceGenerator standard
25+
* cron expression}.
26+
*
27+
* @author Chris Beams
28+
* @since 3.2
29+
* @see Scheduled#cron()
30+
* @see ScheduledTaskRegistrar#setCronTasksList(java.util.List)
31+
* @see org.springframework.scheduling.TaskScheduler
32+
*/
33+
public class CronTask extends TriggerTask {
34+
35+
private String expression;
36+
37+
38+
/**
39+
* Create a new {@code CronTask}.
40+
* @param runnable the underlying task to execute
41+
* @param expression cron expression defining when the task should be executed
42+
*/
43+
public CronTask(Runnable runnable, String expression) {
44+
this(runnable, new CronTrigger(expression));
45+
}
46+
47+
/**
48+
* Create a new {@code CronTask}.
49+
* @param runnable the underlying task to execute
50+
* @param cronTrigger the cron trigger defining when the task should be executed
51+
*/
52+
public CronTask(Runnable runnable, CronTrigger cronTrigger) {
53+
super(runnable, cronTrigger);
54+
this.expression = cronTrigger.getExpression();
55+
}
56+
57+
public String getExpression() {
58+
return expression;
59+
}
60+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
* Copyright 2002-2012 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.scheduling.config;
18+
19+
/**
20+
* {@link Task} implementation defining a {@code Runnable} to be executed at a given
21+
* millisecond interval which may be treated as fixed-rate or fixed-delay depending on
22+
* context.
23+
*
24+
* @author Chris Beams
25+
* @since 3.2
26+
* @see org.springframework.scheduling.annotation.Scheduled#fixedRate()
27+
* @see org.springframework.scheduling.annotation.Scheduled#fixedDelay()
28+
* @see ScheduledTaskRegistrar#setFixedRateTasksList(java.util.List)
29+
* @see ScheduledTaskRegistrar#setFixedDelayTasksList(java.util.List)
30+
* @see org.springframework.scheduling.TaskScheduler
31+
*/
32+
public class IntervalTask extends Task {
33+
34+
private final long interval;
35+
36+
private final long initialDelay;
37+
38+
39+
/**
40+
* Create a new {@code IntervalTask}.
41+
* @param runnable the underlying task to execute
42+
* @param interval how often in milliseconds the task should be executed
43+
* @param initialDelay initial delay before first execution of the task
44+
*/
45+
public IntervalTask(Runnable runnable, long interval, long initialDelay) {
46+
super(runnable);
47+
this.initialDelay = initialDelay;
48+
this.interval = interval;
49+
}
50+
51+
/**
52+
* Create a new {@code IntervalTask} with no initial delay.
53+
* @param runnable the underlying task to execute
54+
* @param interval how often in milliseconds the task should be executed
55+
*/
56+
public IntervalTask(Runnable runnable, long interval) {
57+
this(runnable, interval, 0);
58+
}
59+
60+
61+
public long getInterval() {
62+
return interval;
63+
}
64+
65+
public long getInitialDelay() {
66+
return initialDelay;
67+
}
68+
}

0 commit comments

Comments
 (0)