Spring scheduler which is run after application is started and after midnight
At first you should add @EnableScheduling
annotation for your application config.
The second add @Component
or @Service annotation for your scheduler.
And if you are using Scheduled
annotation it runs automatically after initialization to change it you can use initialDelay
parameter in annotation.
Here is complete example
@Component
public class MyScheduler {
@Scheduled(cron="*/10 * * * * *")
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
}
}
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
}
}