In this article, we will learn about how to schedule a spring boot cron job. an example which runs every 5 minutes. You will see an example of How to schedule spring boot cron job example every 5 minutes.

Spring boot provides @EnableScheduling and @Scheduled annotations, to schedule cron jobs in the spring boot application which runs periodically. 

Let's learn, how to use Spring boot @Scheduled annotation.


Step 1:- Add @EnableScheduling to Spring Boot Application class

@EnableScheduling is a Spring Context module annotation. It internally imports the SchedulingConfiguration via the @Import(SchedulingConfiguration.class)

@SpringBootApplication
@EnableScheduling
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class);
}
}


2. Add Spring boot @Scheduled annotations to methods

Add @Scheduled annotations on methods that you want to schedule.
Note
:- The methods should not contain any arguments. It should be the zero-argument method.

Examples:- 

1. Spring boot cron job

@Scheduled annotation is very flexible to take cron expression

Syntax of corn expression 

Fields in a cron the expression has the following order:

  • seconds
  • minutes
  • hours
  • day-of-month
  • month
  • day-of-week

For example, 0 0 8 * * ? means that the task is executed at 08:00:00 every day.

seconds minutes hours day-of-month month day-of-week
   0       0      8        *         *        ?

For example, 0 10 8 * * ? means that the task is executed at 08:10:00 every day.

seconds minutes hours day-of-month month day-of-week
   0      10      8        *         *        ?

For example, 25 10 8 * * ? means that the task is executed at 08:10:25 every day.

seconds minutes hours day-of-month month day-of-week
  25      10      8        *         *        ?


Below spring boot cron job example which every 5 minutes

@Scheduled(cron = "0 */5 * ? * *")
public void runEvey5Minutes() {
System.out.println("Current time is :: " + LocalDate.now());
}


Time Zone:-
The cron expression is evaluated based on the time zone of the server where the database is running.

To know more about cron schedular expressions which we use in spring boot to schedule a cron job

2. Schedule tasks at a fixed rate

Below spring boot job example, execute at a fixed interval of time:

@Scheduled(initialDelay = 1000, fixedRate = 10000)
public void runEvey10Seconds() {
System.out.println("Current time is :: " + LocalDate.now());
}


3. Schedule task at a fixed delay

Configure a task to run after a fixed delay. In the given example, the duration between the end of the last execution and the start of the next execution is fixed. The task always waits until the previous one is finished.

@Scheduled(fixedDelay = 10000)
public void run() {
System.out.println("Current time is :: " + LocalDate.now());
}


Please comment below if you have any questions on the spring boot cron job schedular.