How to schedule cron job in spring boot to run for every 5 minutes with in specific period

80 Views Asked by At

I have the following code in spring boot, its working fine and job running for every 5 mins.

I want it run between 9:30 AM to 5:30 PM for every 5 minutes.

How to add the the specific time period for below cron expression.

@Scheduled(cron = “0 */5 * ? * *”)

public void runEvey5Minutes() {

System.out.println(“Current time is :: “ + LocalDate.now());

}

2

There are 2 best solutions below

0
Gijs Den Hollander On

Maybe you can do it in one expression, but I doubt it. The hard part is that is starts at 8:30 AM and end at 5:30 PM. So the interval is not symetric, I thinks this make it impossible to parse into one expression.

My idea would be to split it in 3 expression:

- 8:30 - 8:55
 = 0 30/5 8 * ? *

- 9:00AM - 4:59PM  
 = 0 0/5 9-16 * ? *

- 5:00PM - 5:30PM  
 = 0 0-30/5 17 * * ? 

Then you would need 3 methods with the @Scheduled annotation, they should al run the same job of course.

If you want to test if they work, check out this code

Hope this helps

3
Sivaram Rasathurai On

As @Gijs Den Hollander Said,

To run every 5 minutes but only between 8:30 AM and 5:30 PM, you can't achieve this with a single cron expression within Spring Boot's configuration. Cron itself doesn't have a built-in way to specify a time range within an hour.

We need to break it into three cron jobs. Itinvolves creating three separate cron entries in your Spring Boot configuration:

One for every 5 minutes between 9:30 AM and 9:55 AM. Another for every 5 minutes between 9:00 AM and 5:00 PM. A third entry for every 5 minutes between 5:00 PM and 5:30 PM.

0 30/5 9 * * *  # Run every 5 minutes between 9:30 AM and 9:55 AM
0 0/5 10-16 * * *  # Run every 5 minutes between 9:00 AM and 5:00 PM
0 0-30/5 17 * * *  # Run every 5 minutes between 5:00 PM and 5:30 PM

Alternatively You can do

or else you can do below. You can add a condition to check when the scheduler started
@Scheduled(cron = “0 */5 9-15 * * *”)

public void runEvey5Minutes() {

//check the time it falls within your time frame and execute your code
if(condition){
}
}