How to define when my @Scheduled method should be called first time?

Viewed 532

The first time @Scheduled method is called when my project just started(it's not fully up).Can i defined when my @Scheduled method should be called first time(not using initial delay).I want all my @Scheduled method to start execution first time when my server is up.So my startup time will be reduced.

I have used fixed delay Scheduler:

 @Scheduled(fixedDelay = 1800000) // runs in every 30min
public void schedulerFunction(){}
1 Answers

You could implement ApplicationListener and wait for a ContextReadyEvent:

@Component
public class YourClassHavingScheduledMethodimplements ApplicationListener<ContextRefreshedEvent> {

    private boolean contextInitialized = false;

    @Scheduled(...)
    public void someScheduledMethod() {
        if(this.contextInitialized) {
            // Execute logic here
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        this.contextInitialized = true;
    }
}
Related