Explaining @Scheduled annotation
This annotation is used for task scheduling. The trigger information
needs to be provided along with this annotation. You can use the
properties fixedDelay/fixedRate/cron to provide the triggering
information.
- fixedRate makes Spring run the task on periodic intervals even if the last invocation may be still running.
- fixedDelay specifically controls the next execution time when the last execution finishes.
- cron is a feature originating from Unix cron utility and has various options based on your requirements.
Example usage can be as below:
@Scheduled(fixedDelay =30000)
public void demoServiceMethod () {... }
@Scheduled(fixedRate=30000)
public void demoServiceMethod () {... }
@Scheduled(cron="0 0 * * * *")
public void demoServiceMethod () {... }
To use @Scheduled in your spring application, you must first define
below xml namespace and schema location definition in your
application-config.xml file.
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
Above additions are necessary because we will be using annotation based
configurations. Now add below definition to enable annotations.
Next step is to create a class and a method inside the class like below:
public class DemoService
{
@Scheduled(cron="*/5 * * * * ?")
public void demoServiceMethod()
{
System.out.println("Method executed at every 5 seconds. Current time is :: "+ new Date());
}
}
Using @Scheduled annotation would in turn make Spring container understand that the method underneath this annotation would run as a job. Remember that the methods annotated with @Scheduled should not have parameters passed to them. They should not return any values too. If you want the external objects to be used within your @Scheduled methods, you should inject them into the DemoService class using autowiring rather than passing them as parameters to the @Scheduled methods.
And application configuration will look like this:
< ?xml version="1.0" encoding="UTF-8"?>