Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 862
Nawa Avatar asked May 04 '13 18:05

Nawa


People also ask

How do I run a cron job every 12 hours?

->cron('0 */12 * * *'); This cron will run the scheduler at every 12 hours.

What is fixed delay in spring scheduler?

Schedule a Task at Fixed Delay In this case, the duration between the end of the last execution and the start of the next execution is fixed. The task always waits until the previous one is finished. This option should be used when it's mandatory that the previous execution is completed before running again.

How do I start and stop a scheduler in Spring Boot?

3.2. Another way to stop the scheduler would be manually canceling its Future. In the cases with multiple scheduler tasks, then we can maintain the Future map inside of the custom scheduler pool but cancel the corresponding scheduled Future based on scheduler class.

What is @EnableScheduling in Spring Boot?

The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file.


2 Answers

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
    }
}
like image 123
nicholas.hauschild Avatar answered Oct 27 '22 20:10

nicholas.hauschild


A little about this subject, you can use @EventListener annotation.

Here is an example :

@Component
public class MyScheduler {

    @EventListener(ApplicationReadyEvent.class)
    public void onSchedule() {
        doWork();
    }

    public void doWork() {
        // your work required on startup
    }
}
like image 29
Philippe Gibert Avatar answered Oct 27 '22 19:10

Philippe Gibert