Sometimes we come across a situation when we expect a task should execute only at a particular point of time or re-execute within a particular time interval. Simultaneously, our client expects a functionality to be executed at a particular time on an hourly basis, daily basis, weekly basis, monthly basis or even some other as well. In fact, in all these types of situations we implement scheduling to get the requirements fulfilled accordingly. For example, one of the most popular implementation is the report generation at a particular time.
On the other hand, almost every client expects this functionality to have in the project. Currently the most popular one is the PDF report. Consequently, our topic ‘How to Schedule a Task/Job in Java Using Spring Boot Scheduler’ will provide a complete answer on how to do Scheduling using Spring Boot.
Spring Boot has the best support for scheduling wherein we can implement the same in easy & straightforward steps accordingly. There is nothing to explain more on the need of topic ‘How to Schedule a Task/Job in Java Using Spring Boot Scheduler’. Also, every Java developer in his/her professional life will come across this type of scenarios where scheduling will help to solve the project requirement easily. Hence, let’s talk about our topic ‘How to Schedule a Task/Job in Java Using Spring Boot Scheduler?’.
What will you learn from this topic of Spring Boot Scheduler?
1) What is scheduling & where do we use it?
2) How to Schedule a Task/Job in Java Using Spring Boot Scheduler?
3) Equally important, How to use annotations @EnableScheduling & @Scheduled in scheduling context?
4) What are different ways(fixedDelay, fixedRate & Cron Expression) to schedule a task?
5) Further, What is the difference between Point of time & Period of time?
6) What is a cron expression & How to write it?
7) Also, Examples of various brainstorming Cron Expressions?
8) Additionally, How to check an invalid cron expression?
What is scheduling and where is it used?
In a sentence, Scheduling is a process in which we can execute a task in a particular time interval without human intervention. In other words, we can say Scheduling is a process of Executing a task in a loop based on period of time or point of time. For example, suppose our task is to generate a report every day at 9:30AM. Then we can apply scheduling technique here to fulfill our requirements accordingly.
As another example, if we want to send a particular data or file to another application in a particular time interval, then we can do it by using scheduling. Furthermore, places where we can use scheduling are Monthly Bank Statements, Salary Slip generation, Insurance Payment, Electricity Bill, Daily Stand up meetings in Offices, Sprint Planning etc.
What is the difference between Period of time & Point of time ?
Period of time talks about a time gap. It doesn’t have starting date/time. eg. 1 hour, 24 mins, 3 days, 4 months, 40 seconds etc.
Point of time talks about a particular time. Moreover, it has staring date/time. eg. 4 AM, 15th Aug, 26th Jan 9:00AM etc.
How to implement Scheduling in Spring Boot : Steps ?
Step#1 : Create Spring Boot Starter Project : No need to add any other starter dependency.
Step#2 : At Starter class apply @EnableScheduling
Step#3 : Additionally, define a class and apply @Component over class
Step#4 : Finally, Implement a method in above class accordingly, which executes the task and apply @Scheduled(……………)
What is the functionality of @Scheduled?
This annotation instructs Spring Container to execute the method in a loop as per the provided parameters until the application/server stops. However, it uses below concepts to support scheduling.
1) fixed Delay
2) fixed Rate
3) cron expression
Note: Equally important, You can’t write @Scheduled without any input in the bracket, other wise Spring container will throw IllegalStateException: Encountered invalid @Scheduled method ‘generateReport’: Exactly one of the ‘cron’, ‘fixedDelay(String)’, or ‘fixedRate(String)’ attributes is required.
Which Methods can be the candidate to use @Scheduled?
@Scheduled is a method level annotation applied at runtime to mark the method to be scheduled. Any method using @Scheduled needs to satisfy two conditions:
1) The annotated method should not have a return type. Otherwise the return value will be overlooked at runtime.
2) The annotated method should not accept any input parameters.
Examples: How to Schedule a Task/Job in Java Using Spring Boot Scheduler?
We will see the examples of all three concepts but cron expression is the mostly used concept in the industry. fixedRate and fixedDelay supports period of time. However, Cron expression supports both period of time & point of time.
Fixed delay specifies the exact time gap between last method execution completion time and next method start time. On application startup scheduling also starts without time gap. Furthermore, to provide the time gap before the first execution call, use initialDelay. For example, observe the code snippets below:
Note: We can provide fixedDelay input in two ways : Integer and String (To illustrate, look at the above code example)
Integer type : @Scheduled(fixedDelay = 1000)
String type : @Scheduled(fixedDelayString = “1000”)
However, fixedRate denotes the maximum time gap between method call.
Using cron expression
As Cron Expressions are very popular in Unix/Linux OS for scheduling, here also Spring boot includes the same concept internally.
Specifically, the above cron expression indicates to execute the task at every minute 15th second.
How to write a Cron Expression ?
1) There are 6 Asterisks(******) by default in cron expression as shown below. Further each asterisk has some meaning as they denote a value. These values can be assigned as Second, Minute, Hours, Day, Month, WeekDay respectively in sequence as shown below.
Possible values at proper place are also given below.
2) A Cron Expression can accept symbols : * – , / ?
3) Comma denotes possible values
0 0 4,6 * * *
Above expression denotes ‘execute given task every day 4:00:00AM and 6:00:00 AM
4) Dash (-) denotes a range, which means consider all possible values between the range
0 0 4-6 * * *
To illustrate, above expression just denotes ‘execute given task every day 4:00:00AM, 5:00:00AM and 6:00:00 AM’
5) Asterisk(*) denotes any/every/all value
6) Forward slash(/) denotes a period of time
7) Question mark(?) denotes any value, but it is applied only at Day & WeekDay when month value is given.
8) English names can also be used for the day-of-month and day-of-week fields. Use the first three letters of the particular day or month (case does not matter).
Note: For a separate article specific to cron expressions with improvements in Spring 5.3, visit Spring Scheduling Cron Expressions & Improvements.
Cron Expression Exercise with Examples using Spring Boot Scheduler
From the above explanation we learned how to write a cron expression. Consequently, let’s do some exercise on cron expression to make it solid.
Examples Using Point of Time
Ex#1 : Write a cron expression that executes a task everyday at 8 AM
0 0 8 * * *
Ex#2 : Write a cron expression that executes a task everyday at 4 PM
0 0 16 * * *
Ex#3 : Write a cron expression that executes a task at 9AM and 9PM every day
0 0 9,21 * * *
Ex#4 : Write a cron expression that executes a task at 9AM and 8PM every day
0 0 9,20 * * *
Ex#5 : Write a cron expression that executes a task at 8AM, 9AM, 10AM and 11AM every day
0 0 8-11 * * *
Ex#6 : Write a cron expression that executes a task 4 times each after one hour, first at 9PM everyday
0 0 21-00 * * *
Ex#7 : Write a cron expression that executes a task 4 times each after one hour, first at 9PM everyday
0 0 21-00 * * * OR 0 0 21,22,23,00 * * *
Ex#8 : Write a cron expression that executes a task 6:30AM and 9:30PM everyday
0 30 6,21 * * *
Ex#9 : Write a cron expression that executes a task at 0th minute and 0th second
0 0 * * * * ( task will be executed at 00:00:00, 01:00:00, 02:00:00, 03:00:00, ...................23:00:00)
Ex#10 : Write a cron expression that executes a task every minute at 15th second
15 * * * * * ( task will be executed at 00:00:15, 00:01:15, 00:02:15, 00:03:15, ...................00:59:15, 01:00:15, 01:01:15.....etc.)
Examples Using Point of Time Continued…
Ex#11 : Write a cron expression that executes a task 9AM 15th second(9:00:45 AM) every day
15 0 0 * * *
Ex#12 : Write a cron expression that executes a task every year on Aug 25th 9AM
0 0 9 25 8 *
Ex#13 : Write a cron expression that executes a task every month on 7th day at 9:30 AM
0 30 9 7 * *
Ex#14 : Write a cron expression that executes a task every year on Feb 14th 9:00:00 AM
if given day(14th) is Sunday or Tuesday only.
0 0 9 14 2 SUN,TUE
Ex#15 : Write a cron expression that executes a task every year in April everyday at 8AM.
0 0 8 ? 4 ? OR 0 0 8 * 4 *
Note : If month is given, we can use symbol ? in place of * for days & week days.
Ex#16 : How to write a cron expression that executes a task every year to wish a happy new year.
59 59 23 31 12 * OR 0 0 0 1 1 *
Ex#17 : How to write a cron expression that executes a task every year to wish happy birthday on 30th March.
59 59 23 29 3 * OR 0 0 0 30 3 *
Ex#18 : How to write a cron expression that executes a task on the hour 9AM to 6PM weekdays.
0 0 8-18 * * MON-FRI
Examples Using Period of Time
Use slash(/) for period of time at all positions except week days.
Ex#1 : How to write a cron expression that executes a task for every 15 sec gap.
*/15 * * * * *
Ex#2 : How to write a cron expression that executes a task for starting of execution at 0th sec of every minute
and also execute with 30 sec gap
0/30 * * * * *
Ex#3 : How to write a cron expression that executes a task for Every day 11AM and repeat with a gap of 30 min
0 0/30 11 * * * (task will be executed at 11:00:00 AM, 11:30:00 AM, then next day at 11:00:00 AM and so on...)
Ex#4 : How to write a cron expression that executes a task for Every hour 0th min & 0th sec with a gap of 20 secs
0 0/20 * * * *
Ex#5 : At what time the task will be executed by cron expression : 0 0/30 8-10 * * *
Ans: 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day
Ex#6 : At what time the task will be executed by cron expression : 0/20 30/10 10 * * *
Ans: Every Day
Start at – 10:30:00 AM
Next at – 10:40:20 AM, 10:50:40 AM
Next – Next Day at 10:30:00 AM and so on…
Examples of Invalid cron expressions
Ex#1 : 0 * 10 * * *
Of course above cron expression is invalid. Once Asterisk Symbol (*) is used, then next position values are not allowed which makes expression invalid.
Ex#2 : * 0 10 * * * is invalid for the same reason as mentioned above.
◊ This is all about ‘How to Schedule a Task/Job in Java Using Spring Boot Scheduler?’.
In order to get to know more specifically about annotations in Spring Boot Scheduling, kindly visit our article ‘Spring Scheduling Annotations‘.
For all other annotations used in Spring Boot, kindly visit Spring Boot Annotations.
What are the common use cases for Spring Boot Scheduler?
Spring Boot Scheduler is used for various tasks, including batch processing, data synchronization, sending email notifications, and any other task that is recurring or time-sensitive operations.
What’s the difference between fixedRate and fixedDelay in the @Scheduled annotation?
fixedRate specifies the interval between the end of one execution and the start of the next, regardless of how long the execution takes.
fixedDelay specifies the interval between the completion of one execution and the start of the next.
Can we run multiple scheduled tasks in a Spring Boot application?
Yes, we can define and run multiple scheduled tasks in a Spring Boot application by annotating multiple methods with the @Scheduled annotation. Each annotated method will be scheduled independently.
To summarize, In this topic (How to Schedule a Task/Job in Java Using Spring Boot Scheduler?), we learned about What is Scheduling? , and also other technical terms related to scheduling, like How to implement task scheduling using Spring Boot?, What are different ways to implement scheduling, Multiple examples of cron expressions etc. simultaneously. Needless to say, if you finish practicing all the examples, you should feel confident on task Scheduling using Spring Boot. Also, for more details, you can visit official site spring.io.