How to create Scheduled Jobs in Spring Boot?

Dexterous Full Stack Developer with 2+ years of experience creating websites. Skilled at designing API's, databases and user-focused experinces. Also turning complex problems into simple, beautiful and intuitive designs.
Besides this, I am a food and a sunset lover who loves to spend evenings on rooftops..
What is Scheduling?
Scheduling is an automated way of performing tasks at a given specific time or for a specific period.
Spring Boot comes with the support of scheduling jobs or tasks by using @Scheduled annotation and Java Cron expressions. Let us, deep dive, into this amazing feature.
Basic steps for the setup
Create a demo project
Create a new demo project using Spring Initializr.
Enable support for scheduling
To enable support and use the feature throughout the service, one needs to add
@EnableSchedulingin the main Spring Boot class.@EnableScheduling @SpringBootApplication public class PrimeJavaWebserviceApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(PrimeJavaWebserviceApplication.class, args); } }
Facts to keep in mind
The method should not include any input parameters.
The method's return type should be void. Even if you return something, it will get ignored.
The method which needs to be scheduled should be marked with
@Scheduled.
@Scheduled annotation is used to trigger the scheduler.
Scheduling a Job at Fixed Delay
The fixed delay property makes sure that there is a delay of n milliseconds between the finish time of an execution of a task and the start time of the next execution of the task.
When to use: This property is particularly very useful when we need to make sure that only one instance of the task runs all the time. It is helpful when one job is dependent on another.
@Scheduled(fixedDelay = 5000)
public void jobsRunningWithFixedDelay() {
...
}
Let's say the scheduler is triggered at 05:00:00 for the very first time:
1st run -> 05:00:00, job finishes at 05:00:02
2nd run -> 05:00:07, job finishes at 05:00:09
3rd run -> 05:00:14, job finishes at 05:00:16
Let us now look at another parameter known as Initial delay.
@Scheduled(initialDelay=3000, fixedDelay=5000)
public void jobsRunningFixedDelayAndInialDelay() {
...
}
Initial Delay is the time after which the job will be executed for the first time after the initial delay value.
Let's say the scheduler is triggered at 05:00:00 for the very first time:
1st run -> 05:00:00, wait of 3ms and starts at, 05:00:03 ->
job finishes at 05:00:05
2nd run -> 05:00:10, job finishes at 05:00:12
3rd run -> 05:00:17, job finishes at 05:00:19
Scheduling a Job at Fixed Rate
The Fixed rate property runs scheduled jobs at every n milliseconds. This does not depend on the execution of the previous task.
When to use: This feature should be used when each execution of the task is independent. The thing to note is that scheduled jobs don't run parallel by default so the next job won't be executed till the previous one gets complete.
@Scheduled(fixedRate=5000)
public void jobsRunningFixedRate() {
...
}
Let's say the scheduler is triggered at 05:00:00 for the very first time:
1st run -> 05:00:00, job finishes at 05:00:02
2nd run -> 05:00:05, job finishes at 05:00:07
3rd run -> 05:00:10, job finishes at 05:00:12
Scheduling a Job with Cron expressions
A cron expression is a string comprised of 6 or 7 fields, each field separated by white space. The first six fields are mandatory.
<seconds> <minutes> <hours> <day-of-month> <month> <day-of-week> <year>
The last field i.e. <year> is not mandatory.
* (all) means that the event should happen for every time unit.
? (any) is utilized in the <day-of-month> and <day-of -week> fields to denote the arbitrary value. For example, if we want to schedule a script for “15th of every month” irrespective of what day of the week falls on that date, we specify a “?” in the <day-of-week> field.
– (range) determines the value range. For example, “9-10” in the <hour> field means “9th and 10th hours.”
, (values) means multiple values. For example, “SUN, WED, FRI*“* in <day-of-week> field means on the days “Sunday, Wednesday and Friday.”
/ (increments) determines the incremental values. For example, a “5/15” in the <minute> field means “5, 20, 35 and 50 minutes of an hour.”
# means the “N-th” occurrence of a weekday of the month, for example, “third Friday of the month” can be indicated as “6#3”.
Examples :
"0 0 * * * *"= the top of every hour of every day."40 9 19 * ?"= at 9:40 a.m. on the 19th day of every month."0 0 8-10 * * *"= 8, 9 and 10 o'clock every day."15,35 13 ? 6 MON"=At 1:15 p.m. and 1:35 p.m. every Monday in June."0 0 6,19 * * *"= 6:00 AM and 7:00 PM every day."0 0 19 L * ?"= at 7 p.m. on the last day of every month."0 0/30 8-10 * * *"= 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day."0 0 0 25 12 ?"= every Christmas Day at midnight."0 0 0 L * *"= last day of the month at midnight."0 0 0 1W * *"= first weekday of the month at midnight."0 0 0 LW * *"= last weekday of the month at midnight."0 0 0 * * 5L"= last Friday of the month at midnight."0 0 0 * * THUL"= last Thursday of the month at midnight."0 0 0 ? * MON#1"= the first Monday in the month at midnight.
Cron Expression Generators - Sites that I prefer to check my cron expressions are Cron Maker and CronHub .
When to use: With Cron, you can trigger the job to run at that exact time every time.
Conclusion
Schedulers help us to reduce operating costs. We can run any business logic at any specific time and interval. We create scheduled jobs by decorating a method with the @Scheduled annotation. We set the interval of executing by specifying the fixedRate or fixedDelay attribute in the @Scheduled annotation. With the help of Cron expression, we can create more complex schedulers and be time specific.


