By kswaughs | Thursday, February 25, 2016

Spring Boot task scheduler example

Spring Boot provides a simple and easy way to develop and run a Task scheduler without using any xml and bean configurations.

Simply add the annotation @Scheduled on the task scheduler method with required interval time.

In this example, we will see how to use Spring @Scheduled annotation to schedule a task.

Step 1 : pom.xml

pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>1.3.0.RELEASE</version>
</dependency>

Step 2 : Create Scheduler class

MyScheduledTasks
package com.kswaughs.tasks;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyScheduledTasks {

    private static final SimpleDateFormat dateFormat = 
        new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

    @Scheduled(fixedRate = 10000)
    public void sendMailToCustomers() {

        System.out.println("sendMailToCustomers Job ran at " 
            + dateFormat.format(new Date()));

    }
}

Step 3 : Enable Scheduling

BootApp
package com.kswaughs.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@ComponentScan({ "com.kswaughs.tasks" })
public class BootApp {
 
    public static void main(String[] args) {
  
        SpringApplication.run(new Object[] { BootApp.class }, args);

    }

}

Step 4 : Run the application

In this example, Job scheduler is configured to run at an interval of every 10 seconds.

  
sendMailToCustomers Job ran at 02/25/2016 14:30:02
sendMailToCustomers Job ran at 02/25/2016 14:30:12
sendMailToCustomers Job ran at 02/25/2016 14:30:22
sendMailToCustomers Job ran at 02/25/2016 14:30:32
sendMailToCustomers Job ran at 02/25/2016 14:30:42
sendMailToCustomers Job ran at 02/25/2016 14:30:52
sendMailToCustomers Job ran at 02/25/2016 14:31:02
sendMailToCustomers Job ran at 02/25/2016 14:31:12

Recommend this on


12 comments: