INTRODUCTION

We are learning one of important feature of spring boot which is scheduling , which is used to run or execute method in specific period of time. Spring boot provide it using annotation. Using @Scheduled annotation we can perform spring scheduling.




How to implement spring scheduling ?

To schedule method or task , we need to enable the scheduling using @EnableScheduling annotation in your main class and @Scheduled on your method level which you want to perform in specific period of time.


STEPS TO IMPLEMENT SCHEDULING: 

1) Create a spring boot application using spring initializr (https://start.spring.io/)

2) Add @EnableScheduling in your main class

@EnableScheduling
@SpringBootApplication
public class SchedulingTask {

public static void main(String[] args) {

        SpringApplication.run(SchedulingTask .class, args);
      }
}



3) Need to add @Scheduled annotation 

3.1) Scheduled task using cron expression : 

@Component

public class ScheduledClass {

private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss");

@Scheduled(
cron = "0 0 10 * * *")
public void executeCronMethod() {

System.out.println("Code is executed" + formatter.format(LocalDateTime.now()));
}
}


So above cron will run at every 10 AM.


3.2) Scheduled task using fixed rate :

@Component

public class ScheduledClass {

private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss");

@Scheduled(fixedRate = 5000)
public void executeCronMethod() {

System.out.println("Code is executed" + formatter.format(LocalDateTime.now()));
}
}

So we have added scheduled fixedRate is 5000ms which means method will execute every 5 seconds.


3.3) Scheduled task using initial delay : 

When you want to delay the initial execution of task we can use initialDelay,

@Component

public class ScheduledClass {

private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss");

@Scheduled(fixedRate = 5000,
initialDelay = 4000)
public void executeCronMethod() {

System.out.println("Code is executed" + formatter.format(LocalDateTime.now()));

}
}

So above method will execute on every 5 seconds and the initial execution is delayed for 4 seconds.


3.4) Scheduled task using fixedDelay : 

We can delay the method execution at a fixed time period between the end of the previous invocation and the start of the next invocation.


@Component

public class ScheduledClass {

private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss");

@Scheduled(fixedDelay = 5000)
public void executeCronMethod() {

Thread.sleep(3000)
System.out.println("Code is executed" + formatter.format(LocalDateTime.now()));

}
}



SUMMARY : 

So we have learned the spring scheduling in details and how to enable it your application. We can use spring scheduling in batch processing , pushing some data to third party service, file uploading in your application.



USEFUL LINKS :