Search code examples
javaspringcronscheduled-tasks

How to execute a @Scheduled method in java Spring immediately and then according to cron?


I've got a method:

@Scheduled(cron="0 */5 * * * *")
public void syncRoutine() { }

So it runs every 5 minutes.

Is it possible to schedule a method to run immediately first time and then according to cron?


Solution

  • You can combine multiple @Scheduled annotations with @Schedules annotation:

    @Schedules(value = {
            @Scheduled(initialDelay = 15_000,
                    fixedDelay = Long.MAX_VALUE),
            @Scheduled(cron = "0 */5 * * * *")
    })
    public void scheduleFixedDelayTask() {
        System.out.println("Fixed delay task - " +
                System.currentTimeMillis() / 1000);
    }
    

    The task will be executed the first time after the initialDelay (at 15 sec.) value. We make it impossible to repeat with fixedDelay = Long.MAX_VALUE because let cron do it.

    OR

    You can use @PostConstruct and @Scheduled annotation together:

    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    import javax.annotation.PostConstruct;
    
    @Component
    public class ScheduleClass {
    
        @PostConstruct
        public void onStartup() {
            scheduleFixedDelayTask();
        }
    
        @Scheduled(cron = "0 */1 * * * *")
        public void scheduleFixedDelayTask() {
            System.out.println("Fixed delay task - " +
                    System.currentTimeMillis() / 1000);
        }
    }
    

    Normally you don't need to add cron for a task that will run every 5 minutes but I'm assuming this is an example.