@Scheduled annotation

  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.

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.
 

Above additions are necessary because we will be using annotation based configurations. Now add below definition to enable annotations.

<task:annotation-driven>

Next step is to create a class and a method inside the class like below:

publicclassDemoService
{
    @Scheduled(cron="*/5 * * * * ?")
    publicvoiddemoServiceMethod()
    {
        System.out.println("Method executed at every 5 seconds. Current time is :: "+ newDate());
    }
}

 Scheduling using cron expression from properties file 

${cron.expression} –> cron expression will be defined in a properties (xxx.properties) file

sample class will look like this:

package com.howtodoinjava.service;
 
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
 
public class DemoServicePropertiesExample {
 
    @Scheduled(cron = "${cron.expression}")
    public void demoServiceMethod()
    {
        System.out.println("Method executed at every 5 seconds. Current time is :: "+ new Date());
    }
 
}

And application configuration will look like this:

<?xml  version="1.0" encoding="UTF-8"?>
 
    <task:annotation-driven />
    <util:properties id="applicationProps" location="application.properties" />
    <context:property-placeholder properties-ref="applicationProps" />
    <bean id="demoServicePropertiesExample" class="com.howtodoinjava.service.DemoServicePropertiesExample"></bean>
</beans>
Advertisements