How to schedule tasks in Spring Boot?

Let’s say you want to schedule background tasks in your application , may be every ten minutes or at a fixed time every day or during weekends.

How do you do that in Spring Boot?

Spring Boot provides a simple and straightforward solution:

By just using @Scheduled annotation.

Here are the steps in detail:

STEP1: Add spring-boot-starter dependency

Add the below dependency which provides the @Scheduled annotation:

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

STEP2: Add @EnableScheduling annotation on the main class

Along with @SpringBootApplication annotation add @EnableScheduling annotation to the main class:

package com.example.scheduler;

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

@SpringBootApplication
@EnableScheduling
public class SpringschedulerApplication {

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

}

STEP3: Add @Scheduled annotation to the method to be scheduled

Add @Scheduled annotation to the method you want to schedule .

You can pass a parameter to this annotation to customize how to schedule the task:

You want to run it at specified intervals?

Use fixedRate parameter.

You want to provide a specific delay between each run?

Use fixedDelay paramter.

You want to schedule at a particular time/day/day of week/day of month?

Use cron parameter

Here are three examples for each use case:

package com.example.scheduler;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

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

@Component
public class Scheduler {

//run every 2 seconds
	@Scheduled(fixedRate = 2000)
	public void run1() {

		System.out.println("Hello Fixed Rate -------------> Time now is : "
				+ LocalTime.now().format(DateTimeFormatter.ofPattern("hh mm ss")));

	}

  //wait for 1 second between successive runs
	@Scheduled(fixedDelay = 1000)
	public void run2() {

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.println(
				"Hello Fixed Delay, Time now is : " + LocalTime.now().format(DateTimeFormatter.ofPattern("hh mm ss")));
	}


//run during the first second every minute every hour every day of month //every month every day of week
	@Scheduled(cron = "0 * * * * *")
	public void run3() {

		System.out.println("Hello Cron Job **********************> Time now is : "
				+ LocalTime.now().format(DateTimeFormatter.ofPattern("hh mm ss")));
	}
}

Both fixedRate and fixedDelay are in milliseconds.

cron parameter accepts 6 input points.

First one is second (0 to 59)

Second one is minute (0 to 59)

Third one is hour (0 to 23)

Fourth one is day of month (1-31)

Fifth one is month (1 – 12) or (JAN -DEC)

Sixth one is day of week (0 to 7) or (MON – SUN) (Either 0 or 7 can be used to denote Sundays)

Here are few more examples:

https://spring.io/blog/2020/11/10/new-in-spring-5-3-improved-cron-expressions

Here is the output I got after starting the application:

Fixed Rate option is printing the output every second (the time printed out sometimes overlaps – prints the same time successively during successive seconds since it is very quick)

Fixed Delay option is printing every three seconds (waiting for 1 second after the method finishes in 2 seconds)

Cron job option is printing during the first second of every minute.

Here is the link to the entire code:

https://github.com/vijaysrj/springscheduler


Posted

in

by

Tags:

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading