How to describe Spring scheduler which is run after application is started and after 00:00 ?
->cron('0 */12 * * *'); This cron will run the scheduler at every 12 hours.
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.
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.
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.
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
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With