Sunday, January 2, 2011

Spring 3 - Task Scheduling via Annotations: @Scheduled, @Async

In this tutorial we will explore Spring 3's task scheduling support using annotations. We will be using @Scheduled and @Async annotations. Spring also provides scheduling support using the Quartz Scheduler, and via XML configuration (see Spring 3 - Task Scheduling via "scheduled-tasks" Element). We will build our application on top of a simple Spring MVC 3 application. Although MVC is not required, I would like to show how easy it is to integrate.

Why do we need scheduling?
Scheduling is needed if you want to automate the repetition of a task at specific intervals or particular date. You could of course manually watch the time and execute your task, albeit an inefficient task. Who wants to watch the computer every 3 seconds just to hit the Enter key? No one.

The work
We want to run the following sample class at specific intervals:

The task that we're interested is inside the work() method. This example is based on Mark Fisher's example at Task Scheduling Simplifications in Spring 3.0. This method retrieves the thread name, prints the starting and beginning of the method, simulates work by putting the thread in sleep for 10 seconds.

To schedule this using Spring's annotation support, we'll use the @Scheduled annotation.

The @Scheduled Annotation
Spring 3.0 also adds annotation support for both task scheduling and asynchronous method execution.... The @Scheduled annotation can be added to a method along with trigger metadata.

Source: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html
To enable this annotation we need to add the annotation-driven element:

You also need to add the component-scan element. We didn't enable it here since it's already added in the applicationContext.xml (see the accompanying source code at the end of this tutorial)

Let's examine an actual example. We'll create a new class SyncWorker that implements a Worker interface.

Worker

SyncWorker

This worker is synchronous which means if we have to call this worker 10 times, it will block the other workers. They cannot start immediately until the first one is finished. We didn't do anything to make this implementation synchronous. It's the default.

The class that calls this SyncWorker is a scheduler service.
Notice the @Scheduled annotation in the doSchedule() method. This tells Spring to mark this method for task scheduling. Inside the @Scheduled, there's a metadata that describes when the method should be triggered. The following metadata all have the same value (5 seconds) but they are interpreted differently:
fixedDelay=5000
fixedRate=5000 
cron="*/5 * * * * ?"
fixedDelay: An interval-based trigger where the interval is measured from the completion time of the previous task. fixedRate: An interval-based trigger where the interval is measured from the start time of the previous task. cron: A cron-based trigger Running the application gives us the following logs:
Notice how the tasks are run sequentially every 5 seconds.

What if we want to run the workers asynchronously, meaning we don't want to wait for worker 1 to finish before we start worker 2, or worker 3, and so forth? There are valid reasons like efficient use of physical resources and time.

To make a worker asychronous, we add the @Async annotation in the method that needs to be asychronous.

The @Async Annotation
The @Async annotation can be provided on a method so that invocation of that method will occur asynchronously. In other words, the caller will return immediately upon invocation and the actual execution of the method will occur in a task that has been submitted to a Spring TaskExecutor.

Source: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html
To enable this annotation we use the same annotation-driven element.

Let's examine an actual example. We'll create a new class AsyncWorker that implements the Worker interface earlier.

AsyncWorker

This worker is asychronous. The caller (the scheduler service) will return immediately upon invocation.

The class that calls this AsyncWorker is the same scheduler service we had earlier. We
just need to change the value of @Qualifier

Same implementation, except for the asyncWorker reference. It's unbelievably easy.

Running the application gives us the following logs:

Notice how the tasks are run asynchronously.

One final note. Let's examine the XML file that contains the annotation-driven element:

Notice I have added two attributes in the annotation-driven element: executor and scheduler. Both are references to the beans declared at the bottom of the file. The ids of these beans become the default thread name prefixes. See below (taskScheduler-1 and executorWithPoolSizeRange-1):


That's it. We've added scheduling support using the @Scheduled annotation, and asychronous support using the @Async annotation. To see the output, please check the logs. Feel free to modify the MVC app to fit your needs. You might wanna try integrating a web service with scheduling and show the results via MVC. The welcome page is accesible at
http://localhost:8080/spring-mvc-task-scheduling-annotation/krams/main/welcome
The best way to learn further is to try the actual application.

Download the project
You can access the project site at Google's Project Hosting at http://code.google.com/p/spring-mvc-scheduling/

You can download the project as a Maven build. Look for the spring-mvc-task-scheduling-annotation.zip in the Download sections.

You can run the project directly using an embedded server via Maven.
For Tomcat: mvn tomcat:run
For Jetty: mvn jetty:run

If you need to know more about Task Scheduling in Spring 3.0, please visit the following links:

StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring 3 - Task Scheduling via Annotations: @Scheduled, @Async ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

34 comments:

  1. one Quick qtn...can i use both on single method..?? If so are there any issues we can expect..?

    eg:
    @Async
    @Scheduled
    myMethod1(){}

    ReplyDelete
  2. Hi,
    Really a useful example.. Thanks a lot.. Can u tell me how to apply timezone here ? i wanted to schedule task for particular timezone..

    Thanks...

    A.R.U

    ReplyDelete
  3. thanks for the post. I have the same question as the first comment.

    @Async
    @Scheduled(fixedRate=5000)
    public void work()

    Will that help, executing work() method repeatedly with the params set for task:executor?

    ReplyDelete
  4. Hey I have tried the code, But the scheduled task is executing twice......Please help......

    ReplyDelete
  5. Great job!
    Regards

    ReplyDelete
  6. Great article.Thanks.

    ReplyDelete
  7. It's great but We need STS for run Ican't with Other

    ReplyDelete
  8. How the scheduler will trigger ?

    ReplyDelete
  9. You work in spring security is impressive and usefull !!

    ReplyDelete
  10. very nice thank you!

    ReplyDelete
  11. Practically if we think than the task scheduling is a high level of hectic task in itself. To be better at times, the deployment of task management tool is much recommendable but other than that as well the tool which has got specific segment of task tracking and management to be carried out in a precised manner has got the juice up standard in the track. To be ahead with the task tracking and solution, I have been using the task tracking and management tools from Replicon (http://www.replicon.com/olp/task-management-software.aspx) that has tremendous manageability and functionalities that happens to deliver the end result in a precised manner.

    ReplyDelete
  12. We've been a gaggle of volunteers as well as starting off the latest plan in world wide. Your website provided us with beneficial facts. You may have conducted an outstanding work and your whole collection should be happy back.
    online task management

    ReplyDelete
  13. very nice. for more java examples, visit http://java2novice.com site

    ReplyDelete
  14. task scheduling is not an easy job. We tried building our own task management software and soon we realized that we were trying to reinvent the wheel. We have shared our experience at http://www.officetimer.com/blog/task-management-software/.

    ReplyDelete
  15. Sir can i have your email please: can you please explain me about @Configurable(am using Eclipse). i have been trying for two days but am unable to execute the program... so can you please write a sample code and explain the complete all steps..please sir., please

    ReplyDelete
  16. You work in spring security is impressive and usefull
    Shadow fight 2 Mode APK

    ReplyDelete
  17. I have read your blog its very attractive and impressive. I like it your blog.

    Spring online training Spring online training Spring Hibernate online training Spring Hibernate online training Java online training

    spring training in chennai spring hibernate training in chennai

    ReplyDelete


  18. شركات نقل اثاث بالمدينة المنورة تساعدك على نقل اثاثك بامان فلا داعى للقلق مع شركات نقل اثاث بجدة

    عزيزى العميل انت من محبى التنقل باستمرار بالتالى انت بحاجة ماسة وضروية الى الاستعانة بالمختصين في نقل العفش خاصة شركات نقل اثاث بالرياض لان الاستعانة باى من عمالة الشوارع الغير مدربة والتي لا تمتلك خبرة كافية في نقل العفش او الحفاظ علية وليس هذا فقط فقد يؤدى الاستعانة بعمالة الشوارع الى حدوث حالة فقدان وتكسير للاثاث بالتالى التاثير الضار عليك عزيزى العميل

    لا تقلق مطلقاً الان بشأن نقل اي منقولات خاصة بك طالما استعنت بشركة الاول لـ نقل الأثاث في الرياض وخارج الرياض فنحن ليس الوحيدون ولكننا متميزون عن اى مؤسسة أخرى داخل وخارج الدمام وشهرتنا كافضل شركة نقل عفش بينبع
    نقل عفش بجدة

    ReplyDelete