Spring Book – Chapter 19 – Tasks and Scheduling

Annotation-based

Spring 3.0 also adds annotation support for both task scheduling and asynchronous method execution. Below section explain in detail some of the well known annotations in this regard with appropriate code snippets for easy understanding.

@Scheduled

The @Scheduled annotation can be added to a method along with trigger metadata. The various attributes which can be used as metadata to this annotation are fixedDelay, fixedRate and cron. Usage of these attributes in action using code snippets as shown in Listing 20-15 below.

Listing 20-15. Usage of various attributes in @Scheduled annotation

The methods to be scheduled must have void returns and must not expect any arguments. If the method needs to interact with other objects from the Application Context, then those would typically have been provided through dependency injection. Listing 20-16 below shows some “cron” expression which is handy in the form of code snippets.

Listing 20-16. Usage of cron expression in code snippets

The properties are loaded from the file which contains your cron-expressions like this:

@Async

This is an annotation which marks a method as a candidate for asynchronous execution. Can also be used at the type level, in which case all of the type’s methods are considered as asynchronous. Listing 20-17 shows he annotation signature for @Async.

Listing 20-17. @Async annotation signature

Any parameter types can be used for the target method signatures. However the return type of the target method can be either “void” or “java.util.concurrent.Future”. Proxy object of this method will return the “Future” handle will be the actual asynchronous “Future” which can be used to track the result of the asynchronous method execution. Also these methods can expect arguments and they will be invoked in the “normal” way by callers at runtime. Listing 20-18 shows using @Async annotation to a method having no return value.

Listing 20-18. Usage of @Async to a method having no return value

If you would like your method to return a result, the return value should be of type Future, which is mandatory as shown in Listing 20-19 below.

Listing 20-19. Usage of @Async to a method having return value

Page Visitors: 24516

The following two tabs change content below.
Tomcy John

Tomcy John

Blogger & Author at javacodebook
He is an Enterprise Java Specialist holding a degree in Engineering (B-Tech) with over 10 years of experience in several industries. He's currently working as Principal Architect at Emirates Group IT since 2005. Prior to this he has worked with Oracle Corporation and Ernst & Young. His main specialization is on various web technologies and acts as chief mentor and Architect to facilitate incorporating Spring as Corporate Standard in the organization.
Tomcy John

Latest posts by Tomcy John (see all)

Leave a Reply

Your email address will not be published. Required fields are marked *