Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Scheduled to be started every day at a random minute between 4:00AM and 4:30AM

Tags:

spring

cron

as stated in the title of a question, I need to set Spring Scheduler that will run method to load something from database into memory, every day around 4AM

The thing is that I have multiple instances of this server and I don't want all to start executing at the same time cause it will slow down the DB. So I want the time to be at a random minute somewhere between 4:00AM and 4:30AM

So lets say one instance will start everyday at 4:03AM, the other at 4:09AM, third at 4:21AM etc. The execution of query lasts for 1 minute.

Is this possible to do with cron expression, but without using $RANDOM bash (cause I think I dont have it) , or maybe I need to inject this random value some other way into

@Scheduled(cron="* randomMinuteValue 4 * * *")
like image 954
tibortru Avatar asked Dec 07 '16 11:12

tibortru


2 Answers

Using RandomValuePropertySource from Spring

@Scheduled(cron="0 ${random.int[0,30]} 4 * * ?")
like image 116
tibortru Avatar answered Nov 15 '22 10:11

tibortru


In case you have java 8 but not spring boot, you can try the following:

@Scheduled(cron = "0 #{new java.util.Random().nextInt(30)} 4 * * ?")
like image 41
dvtoever Avatar answered Nov 15 '22 09:11

dvtoever