A Guide to Spring Boot Scheduling
if you want your application to perform some task after a fixed interval or based on some schedule, Spring Boot Scheduling can be a handy feature.
Join the DZone community and get the full member experience.
Join For FreeSpring 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.
If you would like to know more about Spring Boot in general, we have a detailed guide on Spring Boot Microservices. However, if you are looking for just a quick intro to Spring Boot Scheduling, then you can simply continue with this post where we set up scheduling in a dummy Spring Boot application.
So 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:
package com.progressivecoder.springbootscheduling;
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.
package com.progressivecoder.springbootscheduling;
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:
package com.progressivecoder.springbootscheduling;
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.
package com.progressivecoder.springbootscheduling;
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:
package com.progressivecoder.springbootscheduling;
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.
With this, 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. You can also find more details about this at the official Spring site.
If you have any comments or queries about this, please do mention them in the comments section below.
Published at DZone with permission of Saurabh Dashora. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments