spring-framework / org.springframework.scheduling.annotation

Package org.springframework.scheduling.annotation

Types

AnnotationAsyncExecutionInterceptor

open class AnnotationAsyncExecutionInterceptor : AsyncExecutionInterceptor

Specialization of AsyncExecutionInterceptor that delegates method execution to an Executor based on the Async annotation. Specifically designed to support use of Async#value() executor qualification mechanism introduced in Spring 3.1.2. Supports detecting qualifier metadata via @Async at the method or declaring class level. See #getExecutorQualifier(Method) for details.

AsyncAnnotationAdvisor

open class AsyncAnnotationAdvisor : AbstractPointcutAdvisor, BeanFactoryAware

Advisor that activates asynchronous method execution through the Async annotation. This annotation can be used at the method and type level in implementation classes as well as in service interfaces.

This advisor detects the EJB 3.1 javax.ejb.Asynchronous annotation as well, treating it exactly like Spring's own Async. Furthermore, a custom async annotation type may get specified through the "asyncAnnotationType" property.

AsyncConfigurerSupport

open class AsyncConfigurerSupport : AsyncConfigurer

A convenience AsyncConfigurer that implements all methods so that the defaults are used. Provides a backward compatible alternative of implementing AsyncConfigurer directly.

AsyncResult

open class AsyncResult<V : Any> : ListenableFuture<V>

A pass-through Future handle that can be used for method signatures which are declared with a Future return type for asynchronous execution.

As of Spring 4.1, this class implements ListenableFuture, not just plain java.util.concurrent.Future, along with the corresponding support in @Async processing.

As of Spring 4.2, this class also supports passing execution exceptions back to the caller.

ProxyAsyncConfiguration

open class ProxyAsyncConfiguration : AbstractAsyncConfiguration

@Configuration class that registers the Spring infrastructure beans necessary to enable proxy-based asynchronous method execution.

SchedulingConfiguration

open class SchedulingConfiguration

@Configuration class that registers a ScheduledAnnotationBeanPostProcessor bean capable of processing Spring's @Scheduled annotation.

This configuration class is automatically imported when using the EnableScheduling annotation. See @EnableScheduling's javadoc for complete usage details.

SchedulingConfigurer

interface SchedulingConfigurer

Optional interface to be implemented by @ classes annotated with @EnableScheduling. Typically used for setting a specific org.springframework.scheduling.TaskScheduler bean to be used when executing scheduled tasks or for registering scheduled tasks in a programmatic fashion as opposed to the declarative approach of using the @Scheduled annotation. For example, this may be necessary when implementing -based tasks, which are not supported by the @Scheduled annotation.

See @EnableScheduling for detailed usage examples.

Annotations

EnableAsync

class EnableAsync

Enables Spring's asynchronous method execution capability, similar to functionality found in Spring's <task:*> XML namespace.

To be used together with @Configuration classes as follows, enabling annotation-driven async processing for an entire Spring application context:

 @Configuration @EnableAsync public class AppConfig { }
MyAsyncBean is a user-defined type with one or more methods annotated with either Spring's @Async annotation, the EJB 3.1 @javax.ejb.Asynchronous annotation, or any custom annotation specified via the #annotation attribute. The aspect is added transparently for any registered bean, for instance via this configuration:
 @Configuration public class AnotherAppConfig { @Bean public MyAsyncBean asyncBean() { return new MyAsyncBean(); } }

By default, Spring will be searching for an associated thread pool definition: either a unique org.springframework.core.task.TaskExecutor bean in the context, or an java.util.concurrent.Executor bean named "taskExecutor" otherwise. If neither of the two is resolvable, a org.springframework.core.task.SimpleAsyncTaskExecutor will be used to process async method invocations. Besides, annotated methods having a void return type cannot transmit any exception back to the caller. By default, such uncaught exceptions are only logged.

To customize all this, implement AsyncConfigurer and provide:

 @Configuration @EnableAsync public class AppConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(7); executor.setMaxPoolSize(42); executor.setQueueCapacity(11); executor.setThreadNamePrefix("MyExecutor-"); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return MyAsyncUncaughtExceptionHandler(); } }

If only one item needs to be customized, null can be returned to keep the default settings. Consider also extending from AsyncConfigurerSupport when possible.

Note: In the above example the ThreadPoolTaskExecutor is not a fully managed Spring bean. Add the @Bean annotation to the getAsyncExecutor() method if you want a fully managed bean. In such circumstances it is no longer necessary to manually call the executor.initialize() method as this will be invoked automatically when the bean is initialized.

For reference, the example above can be compared to the following Spring XML configuration:

<beans> <task:annotation-driven executor="myExecutor" exception-handler="exceptionHandler"/> <task:executor id="myExecutor" pool-size="7-42" queue-capacity="11"/> <bean id="asyncBean" class="com.foo.MyAsyncBean"/> <bean id="exceptionHandler" class="com.foo.MyAsyncUncaughtExceptionHandler"/> </beans> 
The above XML-based and JavaConfig-based examples are equivalent except for the setting of the thread name prefix of the Executor; this is because the <task:executor> element does not expose such an attribute. This demonstrates how the JavaConfig-based approach allows for maximum configurability through direct access to actual componentry.

The #mode attribute controls how advice is applied: If the mode is AdviceMode#PROXY (the default), then the other attributes control the behavior of the proxying. Please note that proxy mode allows for interception of calls through the proxy only; local calls within the same class cannot get intercepted that way.

Note that if the #mode is set to AdviceMode#ASPECTJ, then the value of the #proxyTargetClass attribute will be ignored. Note also that in this case the spring-aspects module JAR must be present on the classpath, with compile-time weaving or load-time weaving applying the aspect to the affected classes. There is no proxy involved in such a scenario; local calls will be intercepted as well.

EnableScheduling

class EnableScheduling

Enables Spring's scheduled task execution capability, similar to functionality found in Spring's <task:*> XML namespace. To be used on @Configuration classes as follows:

 @Configuration @EnableScheduling public class AppConfig { // various @Bean definitions }
This enables detection of @Scheduled annotations on any Spring-managed bean in the container. For example, given a class MyTask
 package com.myco.tasks; public class MyTask { @Scheduled(fixedRate=1000) public void work() { // task execution logic } }
the following configuration would ensure that MyTask.work() is called once every 1000 ms:
 @Configuration @EnableScheduling public class AppConfig { @Bean public MyTask task() { return new MyTask(); } }
Alternatively, if MyTask were annotated with @Component, the following configuration would ensure that its @Scheduled method is invoked at the desired interval:
 @Configuration @EnableScheduling @ComponentScan(basePackages="com.myco.tasks") public class AppConfig { }
Methods annotated with @Scheduled may even be declared directly within @Configuration classes:
 @Configuration @EnableScheduling public class AppConfig { @Scheduled(fixedRate=1000) public void work() { // task execution logic } }

By default, will be searching for an associated scheduler definition: either a unique org.springframework.scheduling.TaskScheduler bean in the context, or a TaskScheduler bean named "taskScheduler" otherwise; the same lookup will also be performed for a java.util.concurrent.ScheduledExecutorService bean. If neither of the two is resolvable, a local single-threaded default scheduler will be created and used within the registrar.

When more control is desired, a @Configuration class may implement SchedulingConfigurer. This allows access to the underlying ScheduledTaskRegistrar instance. For example, the following example demonstrates how to customize the Executor used to execute scheduled tasks:

 @Configuration @EnableScheduling public class AppConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskExecutor()); } @Bean(destroyMethod="shutdown") public Executor taskExecutor() { return Executors.newScheduledThreadPool(100); } }

Note in the example above the use of @Bean(destroyMethod="shutdown"). This ensures that the task executor is properly shut down when the Spring application context itself is closed.

Implementing SchedulingConfigurer also allows for fine-grained control over task registration via the ScheduledTaskRegistrar. For example, the following configures the execution of a particular bean method per a custom Trigger implementation:

 @Configuration @EnableScheduling public class AppConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskScheduler()); taskRegistrar.addTriggerTask( new Runnable() { public void run() { myTask().work(); } }, new CustomTrigger() ); } @Bean(destroyMethod="shutdown") public Executor taskScheduler() { return Executors.newScheduledThreadPool(42); } @Bean public MyTask myTask() { return new MyTask(); } }

For reference, the example above can be compared to the following Spring XML configuration:

<beans> <task:annotation-driven scheduler="taskScheduler"/> <task:scheduler id="taskScheduler" pool-size="42"/> <task:scheduled-tasks scheduler="taskScheduler"> <task:scheduled ref="myTask" method="work" fixed-rate="1000"/> </task:scheduled-tasks> <bean id="myTask" class="com.foo.MyTask"/> </beans> 
The examples are equivalent save that in XML a fixed-rate period is used instead of a custom Trigger implementation; this is because the task: namespace scheduled cannot easily expose such support. This is but one demonstration how the code-based approach allows for maximum configurability through direct access to actual componentry.

Schedules

class Schedules

Container annotation that aggregates several Scheduled annotations.

Can be used natively, declaring several nested Scheduled annotations. Can also be used in conjunction with Java 8's support for repeatable annotations, where Scheduled can simply be declared several times on the same method, implicitly generating this container annotation.

This annotation may be used as a meta-annotation to create custom composed annotations.