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:
Chris Beams
2012-03-14 18:14:28 +02:00
parent 4d5fe57a08
commit 53673d6c59
18 changed files with 659 additions and 112 deletions

View File

@@ -28,6 +28,7 @@ import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.IntervalTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import static org.hamcrest.Matchers.*;
@@ -383,6 +384,45 @@ public class EnableSchedulingTests {
}
@Test
public void withTaskAddedVia_configureTasks() throws InterruptedException {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(SchedulingEnabled_withTaskAddedVia_configureTasks.class);
ctx.refresh();
Thread.sleep(20);
ThreadAwareWorker worker = ctx.getBean(ThreadAwareWorker.class);
ctx.close();
assertThat(worker.executedByThread, startsWith("taskScheduler-"));
}
@Configuration
@EnableScheduling
static class SchedulingEnabled_withTaskAddedVia_configureTasks implements SchedulingConfigurer {
@Bean
public ThreadAwareWorker worker() {
return new ThreadAwareWorker();
}
@Bean
public TaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskScheduler());
taskRegistrar.addFixedRateTask(new IntervalTask(
new Runnable() {
public void run() {
worker().executedByThread = Thread.currentThread().getName();
}
},
10, 0));
}
}
@Test
public void withTriggerTask() throws InterruptedException {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
@@ -421,4 +461,34 @@ public class EnableSchedulingTests {
return scheduler;
}
}
@Test
public void withInitiallyDelayedFixedRateTask() throws InterruptedException {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(FixedRateTaskConfig_withInitialDelay.class);
ctx.refresh();
Thread.sleep(1950);
AtomicInteger counter = ctx.getBean(AtomicInteger.class);
ctx.close();
assertThat(counter.get(), greaterThan(0)); // the @Scheduled method was called
assertThat(counter.get(), lessThanOrEqualTo(10)); // but not more than times the delay allows
}
@EnableScheduling @Configuration
static class FixedRateTaskConfig_withInitialDelay {
@Bean
public AtomicInteger counter() {
return new AtomicInteger();
}
@Scheduled(initialDelay=1000, fixedRate=100)
public void task() {
counter().incrementAndGet();
}
}
}

View File

@@ -22,7 +22,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.List;
import java.util.Properties;
import org.junit.Test;
@@ -33,6 +33,8 @@ import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.IntervalTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.ScheduledMethodRunnable;
@@ -41,6 +43,7 @@ import static org.junit.Assert.*;
/**
* @author Mark Fisher
* @author Juergen Hoeller
* @author Chris Beams
*/
public class ScheduledAnnotationBeanPostProcessorTests {
@@ -57,15 +60,18 @@ public class ScheduledAnnotationBeanPostProcessorTests {
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
Map<Runnable, Long> fixedDelayTasks = (Map<Runnable, Long>)
@SuppressWarnings("unchecked")
List<IntervalTask> fixedDelayTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedDelayTasks");
assertEquals(1, fixedDelayTasks.size());
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) fixedDelayTasks.keySet().iterator().next();
IntervalTask task = fixedDelayTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("fixedDelay", targetMethod.getName());
assertEquals(new Long(5000), fixedDelayTasks.values().iterator().next());
assertEquals(0L, task.getInitialDelay());
assertEquals(5000L, task.getInterval());
}
@Test
@@ -81,15 +87,45 @@ public class ScheduledAnnotationBeanPostProcessorTests {
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
Map<Runnable, Long> fixedRateTasks = (Map<Runnable, Long>)
@SuppressWarnings("unchecked")
List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
assertEquals(1, fixedRateTasks.size());
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) fixedRateTasks.keySet().iterator().next();
IntervalTask task = fixedRateTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("fixedRate", targetMethod.getName());
assertEquals(new Long(3000), fixedRateTasks.values().iterator().next());
assertEquals(0L, task.getInitialDelay());
assertEquals(3000L, task.getInterval());
}
@Test
public void fixedRateTaskWithInitialDelay() {
StaticApplicationContext context = new StaticApplicationContext();
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(
ScheduledAnnotationBeanPostProcessorTests.FixedRateWithInitialDelayTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
Object postProcessor = context.getBean("postProcessor");
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
@SuppressWarnings("unchecked")
List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
assertEquals(1, fixedRateTasks.size());
IntervalTask task = fixedRateTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("fixedRate", targetMethod.getName());
assertEquals(1000L, task.getInitialDelay());
assertEquals(3000L, task.getInterval());
}
@Test
@@ -105,15 +141,17 @@ public class ScheduledAnnotationBeanPostProcessorTests {
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
Map<Runnable, String> cronTasks = (Map<Runnable, String>)
@SuppressWarnings("unchecked")
List<CronTask> cronTasks = (List<CronTask>)
new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
assertEquals(1, cronTasks.size());
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) cronTasks.keySet().iterator().next();
CronTask task = cronTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("cron", targetMethod.getName());
assertEquals("*/7 * * * * ?", cronTasks.values().iterator().next());
assertEquals("*/7 * * * * ?", task.getExpression());
Thread.sleep(10000);
}
@@ -130,15 +168,17 @@ public class ScheduledAnnotationBeanPostProcessorTests {
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
Map<Runnable, Long> fixedRateTasks = (Map<Runnable, Long>)
@SuppressWarnings("unchecked")
List<IntervalTask> fixedRateTasks = (List<IntervalTask>)
new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks");
assertEquals(1, fixedRateTasks.size());
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) fixedRateTasks.keySet().iterator().next();
IntervalTask task = fixedRateTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("checkForUpdates", targetMethod.getName());
assertEquals(new Long(5000), fixedRateTasks.values().iterator().next());
assertEquals(5000L, task.getInterval());
}
@Test
@@ -154,15 +194,17 @@ public class ScheduledAnnotationBeanPostProcessorTests {
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
Map<Runnable, String> cronTasks = (Map<Runnable, String>)
@SuppressWarnings("unchecked")
List<CronTask> cronTasks = (List<CronTask>)
new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
assertEquals(1, cronTasks.size());
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) cronTasks.keySet().iterator().next();
CronTask task = cronTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("generateReport", targetMethod.getName());
assertEquals("0 0 * * * ?", cronTasks.values().iterator().next());
assertEquals("0 0 * * * ?", task.getExpression());
}
@Test
@@ -184,15 +226,17 @@ public class ScheduledAnnotationBeanPostProcessorTests {
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
Map<Runnable, String> cronTasks = (Map<Runnable, String>)
@SuppressWarnings("unchecked")
List<CronTask> cronTasks = (List<CronTask>)
new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
assertEquals(1, cronTasks.size());
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) cronTasks.keySet().iterator().next();
CronTask task = cronTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("x", targetMethod.getName());
assertEquals(businessHoursCronExpression, cronTasks.values().iterator().next());
assertEquals(businessHoursCronExpression, task.getExpression());
}
@Test
@@ -214,15 +258,17 @@ public class ScheduledAnnotationBeanPostProcessorTests {
Object target = context.getBean("target");
ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
Map<Runnable, String> cronTasks = (Map<Runnable, String>)
@SuppressWarnings("unchecked")
List<CronTask> cronTasks = (List<CronTask>)
new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
assertEquals(1, cronTasks.size());
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) cronTasks.keySet().iterator().next();
CronTask task = cronTasks.get(0);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
Object targetObject = runnable.getTarget();
Method targetMethod = runnable.getMethod();
assertEquals(target, targetObject);
assertEquals("y", targetMethod.getName());
assertEquals(businessHoursCronExpression, cronTasks.values().iterator().next());
assertEquals(businessHoursCronExpression, task.getExpression());
}
@Test(expected = BeanCreationException.class)
@@ -237,14 +283,19 @@ public class ScheduledAnnotationBeanPostProcessorTests {
}
@Test(expected = IllegalArgumentException.class)
public void invalidCron() {
public void invalidCron() throws Throwable {
StaticApplicationContext context = new StaticApplicationContext();
BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
BeanDefinition targetDefinition = new RootBeanDefinition(
ScheduledAnnotationBeanPostProcessorTests.InvalidCronTestBean.class);
context.registerBeanDefinition("postProcessor", processorDefinition);
context.registerBeanDefinition("target", targetDefinition);
context.refresh();
try {
context.refresh();
fail("expected exception");
} catch (BeanCreationException ex) {
throw ex.getRootCause();
}
}
@Test(expected = BeanCreationException.class)

View File

@@ -17,9 +17,8 @@
package org.springframework.scheduling.config;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
@@ -31,10 +30,13 @@ import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.support.ScheduledMethodRunnable;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* @author Mark Fisher
* @author Chris Beams
*/
@SuppressWarnings("unchecked")
public class ScheduledTasksBeanDefinitionParserTests {
@@ -64,9 +66,9 @@ public class ScheduledTasksBeanDefinitionParserTests {
@Test
public void checkTarget() {
Map<Runnable, Long> tasks = (Map<Runnable, Long>) new DirectFieldAccessor(
List<IntervalTask> tasks = (List<IntervalTask>) new DirectFieldAccessor(
this.registrar).getPropertyValue("fixedRateTasks");
Runnable runnable = tasks.keySet().iterator().next();
Runnable runnable = tasks.get(0).getRunnable();
assertEquals(ScheduledMethodRunnable.class, runnable.getClass());
Object targetObject = ((ScheduledMethodRunnable) runnable).getTarget();
Method targetMethod = ((ScheduledMethodRunnable) runnable).getMethod();
@@ -76,39 +78,39 @@ public class ScheduledTasksBeanDefinitionParserTests {
@Test
public void fixedRateTasks() {
Map<Runnable, Long> tasks = (Map<Runnable, Long>) new DirectFieldAccessor(
List<IntervalTask> tasks = (List<IntervalTask>) new DirectFieldAccessor(
this.registrar).getPropertyValue("fixedRateTasks");
assertEquals(2, tasks.size());
Collection<Long> values = tasks.values();
assertTrue(values.contains(new Long(1000)));
assertTrue(values.contains(new Long(2000)));
assertEquals(3, tasks.size());
assertEquals(1000L, tasks.get(0).getInterval());
assertEquals(2000L, tasks.get(1).getInterval());
assertEquals(4000L, tasks.get(2).getInterval());
assertEquals(500, tasks.get(2).getInitialDelay());
}
@Test
public void fixedDelayTasks() {
Map<Runnable, Long> tasks = (Map<Runnable, Long>) new DirectFieldAccessor(
List<IntervalTask> tasks = (List<IntervalTask>) new DirectFieldAccessor(
this.registrar).getPropertyValue("fixedDelayTasks");
assertEquals(1, tasks.size());
Long value = tasks.values().iterator().next();
assertEquals(new Long(3000), value);
assertEquals(2, tasks.size());
assertEquals(3000L, tasks.get(0).getInterval());
assertEquals(3500L, tasks.get(1).getInterval());
assertEquals(250, tasks.get(1).getInitialDelay());
}
@Test
public void cronTasks() {
Map<Runnable, String> tasks = (Map<Runnable, String>) new DirectFieldAccessor(
List<CronTask> tasks = (List<CronTask>) new DirectFieldAccessor(
this.registrar).getPropertyValue("cronTasks");
assertEquals(1, tasks.size());
String expression = tasks.values().iterator().next();
assertEquals("*/4 * 9-17 * * MON-FRI", expression);
assertEquals("*/4 * 9-17 * * MON-FRI", tasks.get(0).getExpression());
}
@Test
public void triggerTasks() {
Map<Runnable, Trigger> tasks = (Map<Runnable, Trigger>) new DirectFieldAccessor(
List<TriggerTask> tasks = (List<TriggerTask>) new DirectFieldAccessor(
this.registrar).getPropertyValue("triggerTasks");
assertEquals(1, tasks.size());
Trigger trigger = tasks.values().iterator().next();
assertEquals(TestTrigger.class, trigger.getClass());
assertThat(tasks.get(0).getTrigger(), instanceOf(TestTrigger.class));
}