Search code examples
cron

Task scheduling using cron expression from properties file


I have written a cron job:

@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");
}

I want to get the cron attribute used with @Scheduled annotation to be populated from a external properties file. Currently I am fetching it from a property file inside the application scope. I am able to fetch the value, but not able to use it with @Schedule annotation.


Solution

  • Which version of spring framework are you using? This won't work if it is less than 3.0.1.

    Bug Report here in Spring 3.0.0 and it has been fixed in 3.0.1.

    So if you are using Spring 3.0.1 or greater then following things you have to do to use in cron expression

  • Make an entry in applicationContext.xml for PropertyPlaceHolderConfigurer class that is
    <bean id="placeholderConfig"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:ApplicationProps.properties</value>
            </list>
        </property>
    </bean>
    
    After That Use it in using the @Scheduled method like

    Update: In case if you are using spring boot no need to do anything, below code excerpt should work.

    @Scheduled(cron="${instructionSchedularTime}")
    public void load(){
    }
    

    Note: fixed delay and fixed-rate cann't take property value from placeholder because they take long value. Cron attribute take argument as String so you can use placeholder for that.