使用属性文件中的cron表达式进行任务调度

Sam*_*Sam 13 cron

我写了一份cron工作:

@Scheduled(cron="${process.virtual.account.start}")
public void ecomProcessVirAccOrderPaymentsScheduler() {
    LOGGER.info("Start --->" + this.getClass().getCanonicalName() + ".ecomProcessVirAccOrderPaymentsScheduler() Method");
    schedulerJobHelper.ecomProcessVirAccOrderPaymentsScheduler();
    LOGGER.info("End --->" + this.getClass().getCanonicalName() + ".ecomProcessVirAccOrderPaymentsScheduler() Method");
}
Run Code Online (Sandbox Code Playgroud)

我想@Scheduled从外部属性文件中填充与注释一起使用的cron属性.目前我从应用程序范围内的属性文件中获取它.我能够获取值,但无法将其与@Schedule注释一起使用.

kar*_*lli 26

它在弹簧靴中工作。

@Scheduled(cron="${cronExpression}")
private void testSchedule()  {
    System.out.println("Helloooo");
}
Run Code Online (Sandbox Code Playgroud)

application.properties我有这样的属性如下:

cronExpression=* * * ? * *
Run Code Online (Sandbox Code Playgroud)


Raj*_*eev 18

您使用的是哪个版本的spring框架?如果它小于3.0.1,则不起作用.

Bug 3.0.0中的Bug报告已在3.0.1中修复.

因此,如果您使用的是Spring 3.0.1或更高版本,那么请遵循cron表达式中必须执行的操作

  • 在applicationContext.xml中为PropertyPlaceHolderConfigurer类创建一个条目

    <bean id="placeholderConfig"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:ApplicationProps.properties</value>
            </list>
        </property>
    </bean>
    
    Run Code Online (Sandbox Code Playgroud)

    之后使用@Scheduled方法使用它

    @Scheduled(cron="${instructionSchedularTime}")
    public void load(){
    }
    
    Run Code Online (Sandbox Code Playgroud)

    注意:fixedDelay和fixedRate不能从palceholder获取属性值,因为它们需要很长的值.Cron属性将参数作为String,因此您可以使用占位符.

    • 从Spring 3.2.2开始,你现在有:[fixedDelayString](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html#fixedDelayString--)和[fixedRateString](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html#fixedRateString--). (2认同)