1

I'm fairly new to SpringBoot, and trying to use @Scheduled to execute a certain task with delays. I know there is fixedDelay parameter that can set to have a fixed delay between two executions in a row.

What I need is, is there anyway to set a random delay between every two executions? (I mean every delay is randomly set, but not having a random delay set to fixedDelay)

What I can come up with is, use a fixedDelay, plus a random seconds of Thread.sleep() inside the execution, but feel like there should be a more correct way to do this.

always_beta
  • 229
  • 4
  • 10
  • Does this answer your question? [Spring @Scheduled annotation random delay](https://stackoverflow.com/questions/27869800/spring-scheduled-annotation-random-delay) – Lorelorelore Aug 25 '20 at 09:27
  • @Lorelorelore that is different question. It only randomizes initial delay, not delay between invocations. – talex Aug 25 '20 at 09:41
  • Yes but look at this answer: https://stackoverflow.com/a/41815962/3432678 it mentions the fixedDelayString – Lorelorelore Aug 25 '20 at 09:44
  • @Lorelorelore Unfortunately, from my test, that still makes a fixed delay rather than a random one, my guess is that the expression is evaluated only once but not every time it determines the next delay. – always_beta Aug 25 '20 at 09:50
  • Well yeah, I guess it so... probably you have to consider other approaches for what you're trying to do, without using Scheduled annotation – Lorelorelore Aug 25 '20 at 09:53

1 Answers1

0

Seems like there is no way to make this happen by using spring's api.

I ended up with making 2 schedules with 2 different fixedDelay and both of them execute the same task, e.g: first one with delay of 27 sec while the second has 43 sec, so it looks like the target task being executed with a random delay rather than a fixed one.

always_beta
  • 229
  • 4
  • 10