Implement Scheduler in Spring Boot - Java @ Desk

Wednesday, November 29, 2017

Implement Scheduler in Spring Boot

Implement Scheduler in Spring Boot

Scheduler is implemented in Spring Boot using org.springframework.scheduling.annotation.Scheduled annotation. It takes input as a cron expression along with the time zone.

The @Scheduled annotation is used with a method that performs specific tasks at regular intervals. The package of the scheduler class need to be provided in the Spring Boot main application using scanBasePackages property. During deployment, Spring scans the component provided in scanBasePackages and schedules based on cron provided in scheduler class.

Here is the sample code for the same.
import java.time.LocalDateTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyScheduler {

 final Logger logger = LoggerFactory.getLogger(MyScheduler.class);

 /* scheduled to run at every 5 minutes */
 @Scheduled(cron = "0 0/5 * * * *", zone = "Asia/Calcutta")
 public void run() {
  logger.debug("Scheduler Service Started at " + LocalDateTime.now());
 }

}


Spring Boot Main class
The main class must provide below annotation along with scanBasePackages.
@SpringBootApplication(scanBasePackages = { "com.scheduler" })







No comments:

Post a Comment