Wednesday, October 23, 2013


How to Implement a Task Scheduler/ Job Scheduler in Spring Framework using Annotations?

I had a chance to analyze how the task scheduler works in Spring framework today!! The recent addition of the @Scheduled and @Async into Spring framework 3.0 forced me to tgive them a try! Emphatically, spring framework is remarkable. With a few tweaks in code, everything gets in place as expected. In this article, let me give you a very brief overview on how to implement a scheduled task in spring using @Schedule annotation! This would be a nice tutorial for a newbie and an intermediate Spring programmer! If you intend to have a scheduled job run periodically and if you are using Spring, please read further and get to know the nuances involved.Let us dive into action right away!.
  1. First and foremost, let us decide on incorporating the task:annotation-driven in the applicationContext.xml file. This is the configuration file that would be loaded by the ContextLoaderListener within your spring application. I have decided to have the task:annotation-driven tag within the application since this is where I would be including the beans that would form a part of my service layer and I am going to include the TaskScheduler class a service in my application.
    Next, go ahead and add the xmlns details to your configuration. The following code needs to be added to the applicationContext.xml file in your application.

  2. Further, you have to add the schema location details for the task-annotation driven tag in your applicationContextxml. This is as follows:

  3. Note: If you do not add the configurations given in point # 1 and #2 in your applicationContext.xml where we would be defining the services used in our application (I am conidering that I would have a class containing the scheduled jobs as a service and this would be a part of my services package), you are likely to get the "The prefix 'task' for element '' is not bound" error.
  4. Next, you have to make your Spring container understand that you would be having some scheduled jobs within your application and those tasks are driven by annotations. You can do so by adding the following line to the applicationContext.xml file.

    ?
    1
    2
    <task:annotation-driven>
  5. Now, it is important that the Spring framework should be aware of the class details where you would be using your @Scheduled annotation. For this, let us consider we have a package or.webapp.services.tasks. In this package, let us consider that we have a class MyScheduler.java. This is the class that would contain all the methods which would be invoked as scheduled tasks/jobs in your application. It is important that you add this package in the component-scan tag within your applicationContext.xml as follows:

    ?
    1
    2
  6. Next, we need to code the details of the scheduled job within the class MyScheduler. As a sample, we will have one method testTask. This task would be annotated as @Scheduled with the required attributes. This would in turn make Spring container understand that the method underneath this annotation would be run as a job that is scheduled by the Spring Framework. This can be done as follows:

    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    package org.test.common.utils.Tasks;
    import java.util.Date;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Service;
    @Service
    public class MyScheduler {
       
        @Scheduled(fixedRate = 5000)
        public void process() {
            System.out.println("Invoking testTask at " + new Date());
        }
     
    }
  7. Attributes for @Scheduled Annotation:If you want a job or a task to be run every 5 secondsm then you need to modify the @Scheduled annotation sued above as: @Scheduled(fixedRate = 5000). If you want a time gap of 5 seconds between the end of previous execution and the start of the succeeding execution then you need to modify the @Scheduled annotation as @Scheduled(fixedDelay= 5000). You can also trigger a cron job and define your cron parameters say try running a job at 6.30pm everyday by using @Scheduled(cron="30 18 * * * ")
  8. And that is it! You deploy the application. You would see the 'Invoking testTask at " + current date' getting printed every 5 seconds in your console!
  9. Further, Even if you want to update the db, you can go ahead and get the current session and process this method within a transaction to make db updates on a periodical basis.
  10. Note: Remember that the methods annotated with @Scheduled should not have parameters passed to them. They should not return any values too.If ever you want the external objects to be used within your @Scheduled methods, you should inject them into the MyScheduler class using autowiring rather than passing them as parameters to the @Scheduled methods
If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!Technorati Tags: