简体   繁体   中英

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

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(){}

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM