Spring task scheduler (cron job) example

clock
Spring framework has built in support for scheduled tasks. Here are some examples of spring cron jobs using both annotations and xml configurations.

Download full example > spring cron example (2798)

@Scheduled Annotation

You can use @Scheduled annotation to schedule a task very easily. Below are four simple examples to show how to run cron jobs using spring annotations.

Annotation.java

package com.mycuteblog.spring.schedule;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@EnableScheduling
public class Annotation {
 @Scheduled(fixedDelay = 5000)
 public void fixedDelayTask() {
 System.out.println(new Date() + " This runs in a fixed delay");
 }

 @Scheduled(fixedRate = 6000)
 public void fixedRateTask() {
 System.out.println(new Date() + " This runs in a fixed rate");
 }

 @Scheduled(fixedRate = 7000, initialDelay = 2000)
 public void fixedRateWithInitialDelayTask(){
 System.out.println(new Date() + " This runs in a fixed delay with a initial delay");
 }

 @Scheduled(cron = "10 * * * * *")
 public void cronTask(){
 System.out.println(new Date() + " This runs in a cron schedule");
 }
}

fixedDelay: Run tasks with a fixed delay(in example it’s 5 seconds) between last task end time and next task start time. For example, if task starts at 11:00:00 and it takes 3 seconds to execute next task starts at 11:00:08.

fixedRate: Run tasks with a fixed rate of given time. For example in above example
fixedRateTask() is called every 6 seconds. (ie: 11:00:00, 11:00:06, 11:00:12, …)

initialDelay: This can be used with above examples. This property sets delay for first time run. For example, if program starts at 11:00:00 fixedRateWithInitialDelayTask() will run at 11:00:02, 11:00:09, 11:00:16, …

cron: This can be any cron expression.

output

spring cron job demo output

xml Configuration

A cron job can be set using xml configurations too. Following example shows how you can set above cron jobs using xml.

Xml.java


package com.mycuteblog.spring.schedule;

import java.util.Date;

public class Xml {
public void xmlFixedDelayTask() {
System.out.println(new Date() + " This task runs in fixed delay by xml configuration");
}

public void xmlFixedRateTask() {
System.out.println(new Date() + " This task runs in fixed rate by xml configuration");
}

public void xmlCronTask() {
System.out.println(new Date() + " This task runs in a cron schedule by xml configuration");
}
}

spring.xml


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
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/springcontext.xsd 
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="com.mycuteblog.spring" />

<bean id="xmlScheduledTasks" class="com.mycuteblog.spring.schedule.Xml" />

<task:scheduler id="taskScheduler" pool-size="10" />

<task:scheduled-tasks>
<task:scheduled ref="xmlScheduledTasks" method="xmlFixedDelayTask" fixed-delay="8000"/>
<task:scheduled ref="xmlScheduledTasks" method="xmlFixedRateTask" fixed-rate="10000"/>
<task:scheduled ref="xmlScheduledTasks" method="xmlCronTask" cron="15 * * * * *"/>
</task:scheduled-tasks>

</beans>

I have used maven to build the project. Here is the pom.xml configuration.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.mycuteblog</groupId>
 <artifactId>spring-schedule</artifactId>
 <version>1.0-SNAPSHOT</version>

 <dependencies>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>4.0.6.RELEASE</version>
 </dependency>
 </dependencies>
 
<!--configurations to run project standalone-->
</project>

Finally here is the main class to test above examples.

SpringScheduleDemo.java

package com.mycuteblog.spring.schedule;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringScheduleDemo {
 public static void main(String[] args) {
 ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
 }
}

output
spring xml cron job example

Download full example > spring cron example (2798)

Image courtesy : kylesteed

Enjoyed this article? Share with friends

  • anuragPatle

    Thanks.

    I would be more thankful to you if you add JSON file reading/writing and batch processing with in the same project.

  • vishal biradar

    thanks a lot..after searching for half an hour i got ur solution and its working fine…thanks…

  • dantavo

    Hi I have a question is possible put this service or component into a spring data rest application? If it is possible how I can do that? I tried to put the @EnablingScheduling annotation inside a spring boot main but notthing happend. Any suggestion?

    • Adding @EnableScheduling with @SpringBootApplication annotation should work.

      Here is a working example


      @SpringBootApplication
      @EnableScheduling
      public class WebApplication {

      public static void main(String[] args) {
      SpringApplication.run(WebApplication.class, args);
      }

      @Scheduled(fixedDelay = 5000)
      public void schedule(){
      System.out.println("Hello world!");
      }
      }

      • dantavo

        Yes now run ..it was a dependency problemi…my mistake …. But I have a question. How i can configure my AppConf.java to get the cron placeholder from my property file. I can’t use the
        @Value annotation so I don’t know how I can read that value.
        Thank you

  • Leena Gupta

    Very Nice example and explanation too.
    Please tell me, how could I write Junit for above Annotation.java class?

Subscribe

Subscribe to our email feed and never miss a post

Join Us