Sunday, January 9, 2022

[SOLVED] Spring scheduler which is run after application is started and after midnight

Issue

How to describe Spring scheduler which is run after application is started and after 00:00 ?


Solution

I would do this with two separate constructs.

For after the application starts, use @PostConstuct, and for every night at midnight use @Scheduled with the cron value set. Both are applied to a method.

public class MyClass {
    @PostConstruct
    public void onStartup() {
        doWork();
    }

    @Scheduled(cron="0 0 0 * * ?")
    public void onSchedule() {
        doWork();
    }

    public void doWork() {
        // your work required on startup and at midnight
    }
}


Answered By - nicholas.hauschild