There would be a recurring task that the application or the support engineer needs to perform on a daily/weekly or any specific interval basis. One of the most common method followed for this task is setting up a Cron job in the OS. But what if you do not have a scheduler feature in your OS , Or what if you do not want to tie-up you application to a OS specific feature , Spring-boot is here for your rescue.
It’s often necessary to perform tasks at specific intervals or on a predetermined schedule. This could include tasks such as sending emails, cleaning up old data, or running reports. To automate these tasks, Java developers can use the scheduler feature in Spring Boot.
Spring Boot is a popular Java-based framework that simplifies the development of stand-alone, production-grade applications. One of the many useful features it offers is the ability to schedule tasks using the @Scheduled annotation. This annotation can be added to any method in your application, allowing you to specify the frequency at which the task should run.
In this tutorial, we will explore the basics of using the scheduler feature in Spring Boot, including how to configure and run scheduled tasks.
To use the scheduler feature in Spring Boot, you will need to:
For example, the following code schedules a task to run every minute:
@Scheduled(cron = "0 * * * * *") public void scheduleTask() { System.out.println("Saying Hello!"); }
The expression used in the scueduler annotation is called Cron expressions. Here is a cheat sheet for Cron Expressions
You can also use the fixedRate and fixedDelay parameters to specify the interval at which the task should run.
For example:
@Scheduled(fixedRate = 60000) // runs every minute public void scheduleTask() { System.out.println("Moving files from temp to /opt/temp-backup folder"); }
@Scheduled(fixedDelay = 60000) // runs every minute public void scheduleTask() { System.out.println("Cleaning up temp files"); }
@SpringBootApplication @EnableScheduling public class SpringBootSchedulerTutorialApp{ }
Turn Off concurrent run ( execution of multiple jobs at once ) using
@Scheduled(concurrent = false)
Code is available here : GitHub Project
Happy Coding !
Quick Links
Legal Stuff