2

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(){}
Nivi
  • 71
  • 5
  • What do you exactly mean with `my project is fully up` – Daniel Rafael Wosch Jan 27 '21 at 07:29
  • when my server is up (all my beans are initialized). @DanielWosch – Nivi Jan 27 '21 at 07:38
  • Is your @Scheduled task using any other beans? Because then you may use `@PostConstruct` to execute the logic manually and further define a method with an `@Scheduled` annotation to execute it at a certain time. Because `@PostConstruct` is called after all dependencies have been injected (AFAIR). Means you could depend of the injection of a given Bean and if that been has been injected you are sure that everything is up – Daniel Rafael Wosch Jan 27 '21 at 07:47

1 Answers1

1

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;
    }
}
Hasan Can Saral
  • 2,950
  • 5
  • 43
  • 78