by BehindJava

what is Spring Boot Scheduling and its implementation in Spring Boot

Home » springboot » what is Spring Boot Scheduling and its implementation in Spring Boot

In this tutorial we are going to learn about Spring Scheduling and its implementation in detail.

Spring Boot Scheduling is a handy feature that allows us to schedule jobs in our Spring Boot applications. For example, if you want your application to perform some task after a fixed interval or based on some schedule, this feature can be used.

It also works on the principle of a typical cron job. However, since we can handle it within our application, it becomes relatively easy to perform complex tasks with plain Java code.

let’s start with the process of setting up Spring Boot Scheduler.

1 – The @EnableScheduling Annotation

The first thing required to use the scheduler is to annotate the main class using @EnableScheduling annotation.

@SpringBootApplication
@EnableScheduling
public class SpringBootSchedulingApplication {

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

}

This annotation basically enables the support for scheduling functionality in our application.

2 – Scheduling a Task at Fixed Delay

The first option available is to schedule a task at a fixed delay. This can be done by annotating a method with @Scheduled annotation as below:

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

@Component
public class ScheduledTask {

    @Scheduled(fixedDelay = 1000)
    public void scheduleTask() {
        System.out.println("Printing hello after fixed delay: " + System.currentTimeMillis() / 1000);
    }
}

In the fixed delay option, the duration between the end of the previous task and the beginning of the new task is fixed. In the above example, it is 1000 milliseconds or 1 second. Also, the new task always waits for the previous one to finish.

This behavior is particularly useful when it is imperative that a new task starts only after the previous ends.

3 – Scheduling a Task at Fixed Rate

If we want to have parallel execution of tasks, we need to use the fixed rate parameter. However, to make it really parallel, we also need to use @Async annotation. This will make each task independent of the other tasks.

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

@Component
@EnableAsync
public class ScheduledTask {

    @Async
    @Scheduled(fixedRate = 1000)
    public void scheduleTask() {
        System.out.println("Printing hello after fixed rate: " + System.currentTimeMillis() / 1000);
    }
}

While using the fixed-rate option, we need to be careful not to exceed the size of the memory or the thread pool. If the tasks are long-running, this might lead to Out of Memory Exceptions.

4 – Schedule a Task With Initial Delay

We also have the option of scheduling tasks with an initial delay. This can be done as follows:

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

@Component
public class ScheduledTask {

    @Scheduled(fixedDelay = 1000, initialDelay = 4000)
    public void scheduleTask() {
        System.out.println("Printing hello after fixed delay: " + System.currentTimeMillis() / 1000);
    }
}

By using the initial delay parameter, we ensure that the first execution of the task happens after the initial delay time.

5 – Schedule Task Using Cron Expressions We get a lot of flexibility while using @Scheduled annotation. As an example, we can also use regular cron expressions.

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

@Component
public class ScheduledTask {

    @Scheduled(cron = "* * * ? * *")
    public void scheduleTask() {
        System.out.println("Printing hello after cron delay: " + System.currentTimeMillis() / 1000);
    }
}

Here, the cron expression “* * * ? * *” signifies execution every second. In other words, the task will be executed every second based on the server time.

6 – Parameterize the Spring Boot Scheduling

While you can simply hard-code the schedule value, it could also be useful to be parameterize the schedules. That way, you can change the schedule of a particular task without worrying about recompiling the code.

This can be easily done by using the fixedDelayString, fixedRateString, and cron parameters. See an example below:

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

@Component
public class ScheduledTask {

    @Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds}")
    public void scheduleTask() {
        System.out.println("Printing hello after cron delay: " + System.currentTimeMillis() / 1000);
    }
}

The variable ${fixedDelay.in.milliseconds} can be set up as part of environment variables to your Spring Boot application.

we have looked at the various options provided by the Spring Boot Scheduling mechanism. Basically, by using this feature, it becomes very easy to schedule periodic tasks as part of your application itself.