Search code examples
javaspringspring-bootspring-scheduled

Spring scheduler fixed delay based on time of day


All,

Is there a way I can use spring scheduler which changes the fixedRate based on time of day?

For eg: a method should run with a rate of 1000ms for 10-12am And then switch to 5000ms after 12am

Or do I have to create multiple methods with different crons?


Solution

  • Using @Scheduled, try this:

    @Component
    public class ScheduledConfiguration {
        
        @Scheduled(cron = "* * 10-11 * * ?")
        @Scheduled(cron = "0/5 * 0-9,12-23 * * ?")
        public void execScheduledTask() {
            System.out.println("Now: " + new Date());
        }
        
    }
    

    You need to use two cron configurations:

    * * 10-11 * * ?: every second, of every minute, if the hour part of today is 10 or 11, of every day, of every month, every day of the week.

    0/5 * 0-9,12-23 * * ?: every 5 seconds starting at 0 seconds, of every minute, if the hour part of today is between 0 and 9 or between 12 and 23, of every day, of every month, every day of the week

    See more about this here and here