springcronscheduling

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


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