Spring @Scheduled注释随机延迟

mas*_*roy 13 spring spring-annotations spring-scheduled

我使用@ScheduledSpring框架中的注释来调用方法.但是我的设置中有多个节点,我不希望它们全部在同一时间运行.所以我想将一个随机值设置为初始延迟,以使它们相互抵消.

import org.springframework.scheduling.annotation.Scheduled;

@Scheduled(fixedRate = 600000, initialDelay = <random number between 0 and 10 minutes> )
Run Code Online (Sandbox Code Playgroud)

不幸的是,我只允许在这里使用常量表达式.还有其他方法吗?我想过使用Spring表达式语言.

mek*_*azu 10

要使初始延迟在0到0之间随机,请fixedRate尝试:

@Scheduled(fixedDelayString = "${some.delay}", initialDelayString = "${random.int(${some.delay})}")
Run Code Online (Sandbox Code Playgroud)

some.delay在application.properties或等效项中定义(但选择一个更合适的名称)为10分钟作为属性的位置.

some.delay = 600000
Run Code Online (Sandbox Code Playgroud)

当然,如果你想要懒惰和硬编码,你可以随时使用 ${random.int(600000)}


sk_*_*sk_ 7

您可以通过Spring Expression Language配置initialDelay:

@Scheduled(fixedRate = 600000, initialDelayString = "#{ T(java.util.concurrent.ThreadLocalRandom).current().nextInt(10*60*1000) }" )
Run Code Online (Sandbox Code Playgroud)

我现在没有IDE来测试该代码,因此您可能需要稍微调整一下.


ygl*_*odt 5

在此工作示例中,随机延迟将在 5 到 10 秒之间。

@Scheduled(fixedDelayString = "#{new Double((T(java.lang.Math).random() + 1) * 5000).intValue()}")
Run Code Online (Sandbox Code Playgroud)