如何用Spring 3.0表达式语言参数化@Scheduled(fixedDelay)?

问题描述 投票:0回答:6

当使用 Spring 3.0 功能注释计划任务时,我想将

fixedDelay
设置为我的配置文件中的参数,而不是像当前那样将其硬连接到我的任务类中......

@Scheduled(fixedDelay = 5000)
public void readLog() {
        ...
}

不幸的是,似乎使用 Spring 表达式语言 (SpEL)

@Value
返回一个 String 对象,而该对象又无法按照
fixedDelay
参数的要求自动装箱为 long 值。

java spring configuration annotations scheduling
6个回答
484
投票

Spring v3.2.2 在原来的 3 个长参数的基础上增加了 String 参数来处理这个问题。

fixedDelayString
fixedRateString
initialDelayString
现已推出。

@Scheduled(fixedDelayString = "${my.fixed.delay.prop}")
public void readLog() {
        ...
}

54
投票

您可以使用

@Scheduled
注释,但只能与
cron
参数一起使用:

@Scheduled(cron = "${yourConfiguration.cronExpression}")

您的 5 秒间隔可以表示为

"*/5 * * * * *"
。但是据我了解,您无法提供低于 1 秒的精度。


26
投票

我猜

@Scheduled
注释是没有问题的。因此,也许您的解决方案是使用
task-scheduled
XML 配置。让我们考虑这个例子(复制自Spring doc):

<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="someObject" method="readLog" 
               fixed-rate="#{YourConfigurationBean.stringValue}"/>
</task:scheduled-tasks>

...或者如果从 String 到 Long 的转换不起作用,则类似这样的操作:

<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="someObject" method="readLog"
            fixed-rate="#{T(java.lang.Long).valueOf(YourConfigurationBean.stringValue)}"/>
</task:scheduled-tasks>

再说一遍,我还没有尝试过任何这些设置,但我希望它可以对您有所帮助。


15
投票

在 Spring Boot 2 中,我们可以使用 Spring 表达式语言(SpPL)来实现

@Scheduled
注解属性:

@Scheduled(fixedRateString = "${fixed-rate.in.milliseconds}")
public void fixedRate() {
    // do something here
}

@Scheduled(fixedDelayString = "${fixed-delay.in.milliseconds}")
public void fixedDelay() {
    // do something here
}

@Scheduled(cron = "${cron.expression}")
public void cronExpression() {
    // do something here
}

application.properties
文件将如下所示:

fixed-rate.in.milliseconds=5000
fixed-delay.in.milliseconds=4000
cron.expression=0 15 5 * * FRI

就是这样。这是一篇文章,详细解释了任务调度。


1
投票

我想你可以通过定义一个bean来自己转换该值。 我还没有尝试过,但我想类似于以下的方法可能对你有用:

<bean id="FixedDelayLongValue" class="java.lang.Long"
      factory-method="valueOf">
    <constructor-arg value="#{YourConfigurationBean.stringValue}"/>
</bean>

地点:

<bean id="YourConfigurationBean" class="...">
         <property name="stringValue" value="5000"/>
</bean>

0
投票

如果延迟配置为持续时间,例如

5s
问题中没有漂亮但有效的解决方案:支持占位符中灵活的持续时间解析

@Scheduled(fixedRateString = 
   "#{T(org.springframework.boot.convert.DurationStyle).detectAndParse('${app.update-cache}')}")

我不明白,为什么问题已关闭而 Duration 尚未实现
顺便说一句:我已经尝试过,但没有成功,更漂亮一点:

@Scheduled(fixedRateString = "'PT'+'${app.update-cache}'") and
@Scheduled(fixedRateString = "'PT'.concat('${app.update-cache}')
© www.soinside.com 2019 - 2024. All rights reserved.