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.

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.



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:
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.

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.


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
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

You can download the project as a Maven build. Look for the 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! 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


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


  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..



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

    public void work()

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

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

  5. Great job!

  6. Great article.Thanks.

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

  8. How the scheduler will trigger ?

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

  10. very nice thank you!

  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 ( that has tremendous manageability and functionalities that happens to deliver the end result in a precised manner.

  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

  13. very nice. for more java examples, visit site

  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

  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

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

  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


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

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

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

  19. A retirement plan is very important as it helps the employees to prepare for their future when they will not have the strength to work and earn a living. Luckily, there are financial planners who are always ready to help employees come up with both a saving and retirement plans. These planners by clicking on Leadership Case Study Writing Help

  20. Thank u so much for sharing this sites great job i like it.. :)
    satta matka

  21. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    core java training in Electronic City

    Hibernate Training in electronic city

    spring training in electronic city

    java j2ee training in electronic city

  22. Thank you for sharing your article. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.
    Data Science Training in chennai at Credo Systemz | data science course fees in chennai | data science course in chennai velachery | data science course in chennai omr

  23. Looking for best pyar, dard, bewafa, attitude shayari or status in Hindi launguage? then we have a array of articles, which have all fim dialogue & short poems for ...

  24. I love this post.

    โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
    เพียงแค่คุณสมัคร Gclub กับทางทีมงานของเราเพียงเท่านั้น
    สมัครสมาชิกที่นี่ >>> Gclub online

  25. Very cool!

    เว็บไซต์คาสิโนออนไลน์ที่ได้คุณภาพอับดับ 1 ของประเทศ
    เป็นเว็บไซต์การพนันออนไลน์ที่มีคนมา สมัคร Gclub Royal1688
    และยังมีหวยให้คุณได้เล่น สมัครหวยออนไลน์ ได้เลย
    สมัครสมาชิกที่นี่ >>> Gclub Royal1688

  26. The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Project Centers in Chennai for CSE.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

  27. Welcome to Stardom Resort which Situated "The Land of Royalty" at Jaipur (Rajasthan),Stardom is the dream land for travelers who are intrigued by natural life. Resort strategically located in Jaisinghpura road, Bhankrota, Jaipur (Rajasthan)
    Whether you are looking to bring your family closer on an adventure holiday where you push your limits together through teamwork, or you are just looking to unwind through rest and relaxation at a family beach resort, we provide kid friendly holidays for all your needs and desires. Babies, children, teenagers, adults and everything in-between can find activities to enjoy both together as a family, and independently as well.
    The Resort has28 keys comprising of Suite, Villas and Deluxe rooms, the resort also has need-based conferencing, banqueting, Swimming Pool to relax and rejuvenate your body or soul.
    Enjoy yourpool parties, Corporate Events , Get together , Social Events , Wedding Events at Stardom Resort . Very exclusive place at a very feasible price …

  28. LEGAL DEKHO SERVICES is a Corporate Consultancy Firm handling all Corporate and legal matters on Company Registration, LLP Registration, Trademark Registration, FASSI Registration, PASARA Registration, Civil, Criminal, Business, Commercial, Corporate, Arbitration , Labor & Service subjects in law, in all Statutory Departments and courts as well as Tribunals. An individualized service by members with decades of experience ensures total satisfaction to the clients.

  29. Bawloo Infotech is a premium design agency that focuses on quality, innovation, & speed. We utilized technology to bring results to grow our clients businesses. We pride ourselves in great work ethic, integrity, and end-results. Throughout the years Bawloo Infotech has been able to create stunning, award winning designs in multiple verticals while allowing our clients to obtain an overall better web presence.
    url:Bawloo Infotech is a premium design agency that focuses on quality, innovation, & speed. We utilized technology to bring results to grow our clients businesses. We pride ourselves in great work ethic, integrity, and end-results. Throughout the years Bawloo Infotech has been able to create stunning, award winning designs in multiple verticals while allowing our clients to obtain an overall better web presence.