What is the @Scheduled annotation


Please briefly explain why you feel this question should be reported .

  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 () {… }

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.


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

    @Scheduled(cron="*/5 * * * * ?")
        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"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

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

Manimaran Samuthirapandi 1 year 2021-08-05T05:37:33+02:00 0 Answers 40 views 0

Leave an answer

Captcha Click on image to update the captcha .