Spring scheduler which is run after application is started and after midnight

Nawa picture Nawa · May 4, 2013 · Viewed 17.8k times · Source

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

Answer

nicholas.hauschild picture nicholas.hauschild · May 4, 2013

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