Search code examples
javaspringspring-bootcron

Spring boot: @Scheduler that updates cron espression without restarting


I Need to schedule a task on Spring Boot that reads a cron espression from the database. I did this using the @Scheduled annotation and reading a property inside a database, but my client is asking to be able to update the cron expression in the database and having it affect the scheduled without restarting the application. I know this isnt possible with the @Scheduled annotation, but would It be possible to schedule another task that extracts the cron expression every hour, and then feed the updated expression to the actual scheduled that executes the task? Basically updating the variable that Is Fed to the second scheduled. If this isnt possible, do you know any alternative ways to achieve this without using the @Scheduled annotation? Thank you.


Solution

  • Solved this using SchedulingConfigurer, here's a sample:

    @Configuration
    @EnableScheduling
    public class BatchConfig implements SchedulingConfigurer {
    
      
    
        @Override
        public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
            taskRegistrar.addTriggerTask(new Runnable() {
                @Override
                public void run() {
    
    
                    //run your code here
                }
            }, new Trigger() {
                @Override
                public Date nextExecutionTime(TriggerContext triggerContext) {
                 //extract cron from database
    
                    
    
                    CronTrigger trigger = new CronTrigger(new CronTrigger(//insert cron that you got from database));
                    return trigger.nextExecutionTime(triggerContext);
                }
            });
        }
    }