Spring @Scheduled批注随机延迟 [英] Spring @Scheduled annotation random delay

查看:1311
本文介绍了Spring @Scheduled批注随机延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring框架中的@Scheduled注释来调用方法.但是我的设置中有多个节点,我不希望它们都完全同时运行.因此,我想为初始延迟设置一个随机值,以使它们彼此抵消.

I am using the @Scheduled annotation from Spring framework to invoke a method. But I have multiple nodes in my setup and I do not want them to all run at exactly the same time. So I'd like to set a random value to the initial delay to offset them from each other.

import org.springframework.scheduling.annotation.Scheduled;

@Scheduled(fixedRate = 600000, initialDelay = <random number between 0 and 10 minutes> )

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

Unfortunately, I am only allowed to use a constant expression here. Is there any other way around this? I thought of using Spring expression language.

推荐答案

您可以通过Spring表达式语言配置initialDelay:

You can configure the initialDelay through Spring Expression Language:

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

我目前没有IDE可以测试该代码,因此您可能需要稍作修改.

I don't have an IDE to test that code right now, so you may need to adapt that a bit.

这篇关于Spring @Scheduled批注随机延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆