Tuesday, 2 June 2015

How to schedule a task in SPRING?

Hi! reader. Spring provides support for scheduling jobs based on cron expression. This scheduling is possible with use of @Scheduled annotation.

@Scheduled annotation:

This annotation is used for task scheduling.  One can use the properties fixedDelay/fixedRate/cron to provide the triggering information.
  1. fixedRate makes Spring run the task on periodic intervals even if the last invocation may be still running.
  2. fixedDelay specifically controls the next execution time when the last execution finishes.
  3. cron is a feature originating from Unix cron utility and has various options based on your requirements.
To use @Scheduled in spring application, one must first define below xml namespace and schema location definition in your application-config.xml file.

Above additions are necessary because we will be using annotation based configurations. Now add this definition to enable annotations.  <task:annotation-driven>
Next step is to annotate the method (or class) to be scheduled:
        @Scheduled(cron="*/2 * * * * ?")
    //@Scheduled(fixedDelay = 2000)
    //@Scheduled(fixedRate = 2000)
         public void syncMethod(){
             System.out.println("This method is executed every 2 second daily");
             }


To generate cron-expression: visit Cron-generator
To check your cron-expression: visit Cron-Checker

Enjoy auto-scheduling jobs (y)

No comments:

Post a Comment