如何使用Spring 3.0表达式语言参数化@Scheduled(fixedDelay)?
当使用 Spring 3.0 功能注释计划任务时,我想将 fixedDelay
设置为我的配置文件中的参数,而不是像当前那样将其硬连接到我的任务类中......
@Scheduled(fixedDelay = 5000)
public void readLog() {
...
}
不幸的是似乎通过 Spring 表达式语言 (SpEL) @Value
返回一个 String 对象,而该对象又无法按照 fixedDelay 的要求自动装箱为 long 值
参数。
When using the Spring 3.0 capability to annotate a scheduled task, I would like to set the fixedDelay
as parameter from my configuration file, instead of hard-wiring it into my task class, like currently...
@Scheduled(fixedDelay = 5000)
public void readLog() {
...
}
Unfortunately it seems that with the means of the Spring Expression Language (SpEL) @Value
returns a String object which in turn is not able to be auto-boxed to a long value as required by the fixedDelay
parameter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Spring v3.2.2在原来的3个长参数的基础上增加了String参数来处理这个问题。
fixedDelayString
、fixedRateString
和initialDelayString
现在也可用。Spring v3.2.2 has added String parameters to the original 3 long parameters to handle this.
fixedDelayString
,fixedRateString
andinitialDelayString
are now available too.您可以使用 @Scheduled 注释,但只能与 cron 参数一起使用:
您的 5 秒间隔可以表示为
"*/5 * * * * * “
。但是据我了解,您无法提供低于 1 秒的精度。You can use the
@Scheduled
annotation, but together with thecron
parameter only:Your 5 seconds interval could be expressed as
"*/5 * * * * *"
. However as I understand you cannot provide less than 1 second precision.我猜
@Scheduled
注释是没有问题的。因此,也许您的解决方案是使用任务计划
XML 配置。让我们考虑这个例子(复制自 Spring doc ):...或者如果从 String 到 Long 的转换不起作用,类似这样的事情会:
同样,我还没有尝试过任何这些设置,但我希望它可以对您有所帮助。
I guess the
@Scheduled
annotation is out of question. So maybe a solution for you would be to usetask-scheduled
XML configuration. Let's consider this example (copied from Spring doc):... or if the cast from String to Long didn't work, something like this would:
Again, I haven't tried any of these setups, but I hope it might help you a bit.
在 Spring Boot 2 中,我们可以使用 Spring 表达式语言 (SpPL) 来实现 @Scheduled 注释属性:
application.properties
文件将如下所示:就是这样。这是一篇文章,详细解释了任务调度。
In Spring Boot 2, we can use Spring Expression Language (SpPL) for
@Scheduled
annotation properties:The
application.properties
file will look like this:That's it. Here is an article that explains task scheduling in detail.
我想你可以通过定义一个bean来自己转换该值。 我还没有尝试过,但我想类似于以下的方法可能对您有用:
其中:
I guess you can convert the value yourself by defining a bean. I haven't tried that, but I guess the approach similar to the following might be useful for you:
where:
如果延迟配置为持续时间,例如
5s
,则 问题:支持占位符中灵活的持续时间解析我不明白,为什么问题已关闭并且持续时间尚未实现
顺便说一句:我已经尝试过,但没有成功,更漂亮一点:
In case of delay configured as Duration, e.g.
5s
, there are not pretty, but working solution from issues: support flexible duration parsing in placeholdersI do not understand, why issue is closed and Duration is not realized yet
BTW: I've tried, but without success, a little more pretty: