繁体   English   中英

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

[英]How to parameterize @Scheduled(fixedDelay) with Spring 3.0 expression language?

当使用Spring 3.0功能来注释计划任务时,我想将fixedDelay设置为我的配置文件中的参数,而不是将其硬连接到我的任务类中,就像当前...

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

不幸的是,似乎使用Spring表达式语言(SpEL)的方法@Value返回一个String对象,而该对象又无法按照fixedDelay参数的要求自动fixedDelay长值。

Spring v3.2.2已将String参数添加到原始的3个long参数中以处理此问题。 fixedDelayStringfixedRateStringinitialDelayString现在也可用。

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

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

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

您的5秒间隔可以表示为"*/5 * * * * *" 但据我了解,你不能提供不到1秒的精度。

我想@Scheduled注释是@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>

同样,我还没有尝试过任何这些设置,但我希望它可能对你有所帮助。

我想你可以通过定义一个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>

在Spring Boot 2中,我们可以将Spring Expression Language(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

而已。 这是一篇详细解释任务调度的文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM