0

We have Spring scheduled job with cron expression which is configured in database. I need to change schedule time without restart the application server. But i could not achieve this and i have tried many ways using SO solutions in other link, but none worked for me. Below is my code snippet.

Scheduler time will get from database during dispatcher servlet initializing and assign in the property variable test.scheduler

Scheduler.java

 @Scheduled(cron = "${test.scheduler}")
 public void testScheduler() {
     System.out.println("Dynamic Scheduler Run Test"+new java.util.Date().getTime());
 }

dispatcher-servlet.xml

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="properties">
            <bean class="org.apache.commons.configuration.ConfigurationConverter" factory-method="getProperties">
                <constructor-arg>
                    <bean class="org.apache.commons.configuration.DatabaseConfiguration">
                    <constructor-arg>
                        <ref bean="dataSource" />
                    </constructor-arg>
                    <constructor-arg value="TABLE_NAME" /> 
                    <constructor-arg value="TABLE_KEY" /> 
                    <constructor-arg value="TABLE_VALUE" />
                    </bean>
                </constructor-arg>
            </bean>
        </property>
    </bean>

From the table (TABLE_NAME), there is column's key is test.scheduler & value is 0 0/5 * * * ?

deadend
  • 1,286
  • 6
  • 31
  • 52
  • SpEL won't let you do this. Are you using Spring Boot? If so, you could use Spring Actuator to trigger a refresh event. I can post an example solution if you are happy with this approach. – Daniel Scarfe Aug 05 '21 at 10:31
  • @daniel.scarfe am using Spring MVC not spring boot. i tried to extend DatabaseConfiguration and override the propert value but not working – deadend Aug 05 '21 at 10:35

1 Answers1

1

As far as I am aware, SpEL won't let you change the value of your scheduler once it has been initialised.

If you are using Spring Boot, you will be able to use Actuator to trigger a refreshed event:-

http://localhost:8080/actuator/refresh

In which case, you can make the bean implement RefreshedScope and update your scheduler by triggering the RefreshScopeRefreshedEvent:

@EventListener(RefreshScopeRefreshedEvent.class)
public void onRefresh(RefreshScopeRefreshedEvent event) {
    // Read the database, update the scheduler.
}

An example implementation of this can be seen here. This might not be the perfect solution to your problems but I am posting it for visibility and to help others.

An alternative solution may involve using a Trigger to determine the next execution time. An example StackOverflow answer can be seen here.

Daniel Scarfe
  • 256
  • 1
  • 7