➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
Scheduling in Spring Boot | Executing a task in a loop (multiple times), based on a period (or) point of time is called scheduling.
Period of time: Time gap
Ex: 5 minutes, 6 hours, 3 days, 2 months, etc.
Point of time: Exact Date and Time
Ex: Mar 31st 9 AM, 12th JAN 6 PM, etc.
Use cases of Scheduling:-
- Bank Account Statement (sent by email) each month
- Credit Card Billing
- Reports for Business**
- EMI Payment details
- Employee Salary Payment, PaySlip Generation
- Mobile Auto Recharge
- Insurance Policy Payment
Normally web applications are executed using a Server. When the Server is started, then Scheduling is started as a background thread (daemon thread) which will not affect the actual flow and use of the application. When the application is stopped then scheduling is stopped.
Base Factor: NANO SEC
- 1 MICRO = 1000 x NANO SEC;
- 1 MILLI = 1000 x MICRO SEC;
- 1 SECOND = 1000 x MILLI SEC;
- 1 MINUTE = 60 x SECOND;
- 1 HOUR = 60 x MINUTE;
- 1 DAY = 24 x HOUR;
Our Spring Boot Application, will not activate Scheduling default because every application may not need this.
Step 1:- To work with Scheduling add annotation: @EnableScheduling at starter class.
Step 2:- Define one class and method, Add annotation: @Scheduled over the method.
@Scheduled is defined in 3 ways:-
- fixedDelay
- fixedRate
- cron (cron expression | cron jobs)
Among these 3 ways, cron is the most used.
Fixed Delay in Scheduling
fixedDelay
: It comes under the period of time. It takes a number (input) in Mill seconds. When the application is started, the Spring container creates an object and call method in Loop.
initialDelay (in mill sec): This is used to provide a time gap between application startup and first method call.
Add Annotation over starter class: @EnableScheduling:-
package com.knowprogram.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SchedulingDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingDemoApplication.class, args);
}
}
Define one Scheduler class:-
package com.knowprogram.demo;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class StudentReport {
@Scheduled(initialDelay = 3000, fixedDelay = 5000)
public void generateReport() {
System.out.println("StudentReport.generateReport(): " + new Date());
// code
}
}
@Scheduled(initialDelay = 5000)
means that every 5 seconds method will get executed after starting the application. @Scheduled(initialDelay = 3000, fixedDelay = 5000)
means the first method call will be after 3 seconds of the application start, and later it will get called after every 5 seconds. It will be a daemon thread, which will not affect the actual flow and use of the application. When the application is stopped then scheduling is stopped.
Method execution time may vary. For example, the first time it took 5 seconds, 2nd time it took 3 seconds, but once the method execution is finished then it will always wait till the specified time (fixedDelay).
If we define @Scheduled without any value (or attribute) then it gives IllegalStateException: Encountered invalid @Scheduled method 'generateReport': Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required.
Providing -ve value to Scheduling is an invalid case. @Scheduled(fixedDelay = -5555)
(same exception as like above).
Fixed Rate in Scheduling
The fixedRate is the max time gap between method executions.
Case#1: If fixedRate > Method execution time
Time gap = fixedRate – method execution time.
Assume fixedRate is 5 seconds, and method execution time is 2 seconds, therefore time gap = 5 – 2 = 3 seconds. When 1st method call is completed, it will wait for 3 seconds and then again it will the method. If the method execution time varies due to any circumstances then the gap time will also vary.
Case#2: If fixedRate <= method execution time.
Time gap = Zero (0).
Assume fixedRate is 1 second, and method execution time is 2 seconds then time gap = 0. When 1st method call is completed then immediately 2nd method call will be performed without any time gap.
Here, we can also add initialDelay. @Scheduled(initialDelay = 3000, fixedRate = 5000)
=> It means 1st method call will happen after 3 seconds of the application start. The 2nd method call will happen after either 5 seconds – method execution time (if method execution time < 5 seconds) or no time gap (if method execution time > 5 seconds).
package com.knowprogram.demo;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class StudentReport {
@Scheduled(initialDelay = 3000, fixedRate = 5000)
public void generateReport() {
System.out.println("StudentReport.generateReport(): " + new Date());
// code
}
}
Scheduling with Cron Expression
Compared to fixedDelay and fixedRate, cron expression is more popular. Cron expression by default provides the point of time, by it also supports period of time.
Positions | SEC | MIN | HOUR | DAY | MONTH | WEEK-DAY |
Possible Values | 0-59 | 0-59 | 0-23 | 1-31 | 1-12 | SUN-SAT |
We can even add a few symbols in cron expressions:-
* | all/any/every |
, | possible values (multiple values) |
– | Range (from – to) |
/ | Period of Time |
? | all/every/any [Applied to position only DAY and WEEK-DAY when the month is provided. |
Example-1: cron = "0 0 10 * * *"
Execute the given task (method), every day at 10:00:00 AM
More examples of cron expressions:-
Cron Expression | Meaning |
0 0 22 * * * | Every day at 22:00:00 (10:00:00 PM). |
0 30 11 * * * | Every day at 11:30:00 AM. |
0 0 9,10,11 * * * | Every day 3 times:- 9:00:00 AM, 10:00:00 AM, and 11:00:00 AM. |
0 0 7-10 * * * | Every day 4 times:- 7:00:00 AM, 8:00:00 AM 9:00:00 AM, and 10:00:00 AM. |
0 10 * * * * | Every hour 10th minute. Example:- If the application started at 9:45:00 then 1st execution at 10:10:00, the next execution at 11:10:00, the next at 12:10:00, the next at 13:10:00 (1:10:00 PM), and so on. |
0 30 * * * * | Every hour 30th minute. Example:- If the application started at 9:45:00 then 1st execution at 10:30:00, the next execution at 11:30:00, the next at 12:30:00, the next at 13:30:00 (1:30:00 PM), and so on. |
10 * * * * * | For every minute 10th second. Example:- If the application started at 9:45:00 then 1st execution at 9:45:10, the next execution at 9:46:10, the next at 9:47:10, the next at 9:48:10, and so on. |
package com.knowprogram.demo;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class StudentReport {
@Scheduled(cron = "10 * * * * *")
public void generateReport() {
System.out.println("StudentReport.generateReport(): " + new Date());
// code
}
}
What will happen if any exception occurs in the method execution of the cron Job? That current execution will be stopped. Based on the cron expression next method call is made.
Example: cron = "20 * * * *"
IllegalStateException: Encountered invalid @Scheduled method ‘generateReport’: Cron expression must consist of 6 fields (found 5 in “20 * * * *”)
Example: cron = "20 * * * * * *"
IllegalStateException: Encountered invalid @Scheduled method ‘generateReport’: Cron expression must consist of 6 fields (found 7 in “20 * * * * * *”)
Cron Expression | Meaning |
* * * * * * | Execute the task for every second (execute the given task, back to back with a gap of one second). |
1 * * * * * | Execute the given task, on every minute 1st second. Assume the application starts at 9:15:25 AM then 1st execution will be at 9:16:01 AM, next at 9:17:01 AM, next at 9:18:01 AM, and so on. |
0 * * * * * | Execute the given task, every minute starting. Assume the application starts at 9:15:25 AM then 1st execution will be at 9:16:00 AM, next at 9:17:00 AM, next at 9:18:00 AM, and so on. |
The “/” symbol represents the point of time.
Cron Expression | Meaning |
*/10 * * * * * | After every 10 seconds gap. |
* * | After every 10 minutes gap. |
* * * | After every 10 hours gap. |
* * * * | After every 10 days gap. |
If we provide hours then we must specify minutes and second position values.
Example: cron = "0 * 9 * * *"
Invalid expression.
If we provide minutes then we must specify the seconds position values.
Example: cron = * 10 * * * *
Invalid Expression.
Cron Expression | Meaning |
0 0 9 1 * * | Execute given task on every month 1st 9:00:00 AM. |
0 0 9 1 * MON-SAT | Execute the given task on every month 1st at 9:00:00 AM, if the weekday is not Sunday. |
0 0 9 15 3 FRI | Execute the given task on 15th March at 9:00:00 AM if the weekday is Friday. |
When we provide a month, we must specify DAY and WEEK DAY.
Example: cron = 0 0 9 * 3 *
Invalid expression
If month is provided then to represent all/any/every for DAY and WEEK DAY we must use the “?” instead of the “*” symbol.
Example: cron = 0 0 9 ? 3 ?
March every day at 9:00:00 AM.
Write a cron expression to execute the task on a given year.
Not possible as of now.
Our expression supports up to month, if we specify month, then it is applied for every year.
Example: cron = "0 0 9 1 11 ?"
Execute given task every year, Nov-1st 9:00:00 AM
Mixing of Period and Point
Always Starts with the point of time, and then adds period of time.
Example: cron = "0 0/15 9 1 1 ?"
Every year 1st Jan 9:00:00 AM with a gap of 15 minutes.
1st execution: 1st Jan 9:00:00 AM
Next Execution: Execute with Gap of 15 mins
9:15:00 AM => 9:30:00 AM => 9:45:00 AM => next year.
Example: cron= "0 0/30 8-10 * * *"
Every day 8:00:00 AM with a gap of 30 minutes till 10:: AM.
Execution times: 8:00:00 => 8:30:00 => 9:00:00 => 9:30:00 => 10:00:00 => 10:30:00 => next day.
Example: cron= 0/10 * * * * *
Every minute 0th second with a gap of 10 seconds.
Execution times (assume application starts at 10:08:00 AM): 10:08:00 => 10:08:10 => 10:08:20 => 10:08:30, and so on.
Cron Expression | Meaning |
0 0 * * * * | Every hour starting. Example: 9:00:00AM, 10:00:00 AM. |
*/10 * * * * * | Every 10-second gap. |
0 0 8-10 * * * | Every Day, 8:00:00 AM, 9:00:00AM and 10:00:00AM |
0 0 6,19 * * * | Every Day execute the task at 6 AM and 7 PM. |
0 0 9-17 * * MON-FRI | Every day if the day is not Saturday or Sunday at 9:00:00 AM, 10:00:00 AM, 11:00:00 AM till 17:00:00 (5:00:00PM). |
0 0 0 25 12 ? | Every Christmas Day at midnight. |
Write a cron expression to represent 1 second before the new year.59 59 23 31 12 ?
Write a cron expression to represent Nov Month every day (if the day is not SAT, SUN) at midnight (12 NOON / 12 AM).0 0 0 ? 11 MON-FRI
The weekday must be in the upper case. Expression 0 0 0 ? 11 mon-fri
is invalid.
Write a cron expression to represent FEB 14th, 9 AM and 9 PM, if not MONDAY.0 0 9,21 14 2 TUE-SUN
Or, 0 0 9,21 14 2 TUE,WED,THR,FRI,SAT,SUN
Write a cron expression to represent OCT every day and all weekday 9 AM to 6 PM (9 AM, 10 AM, 11 AM, 12 PM, 1 PM…. 6 PM) for every one hour.0 0 9-18 ? 10 ?
Or, 0 0 9-18 ? 10 SUN-SAT
Valid crons
0 0 * ? 10 ?
* * * * * *
Invalid crons
? ? ? ? ? ?
* * * * *
* * * * * * *
0 0 12 ? * SAT
00 00 12 ? * SAT
Special Cases
When we mention hours then we must mention minutes and seconds. According to this, when we mention minutes then we must mention seconds but this is not the case.
Cron = * 10 * * * *
(Every second of the 10th minute in every hour).
As per documentation, it is invalid but it is working.
Sometimes for invalid expressions, we won’t get any error but we may get unexpected results. For example: cron = "* 48 * * * *"
, hour can’t be 48 but we won’t get any error. It’s a bug.
For more information:- Manpage
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!