My application is based on spring boot. I want to create a task which should be run only once after application has been started.
Currently, I am looking into two solutions:
Using @Scheduled
and boolean property which should determine whether the logic shold be run or not.
@Scheduled
public void method(){
if(method_run_propery){
//do something;
}
}
Using Quartz. But I have not used before.
Please, tell me what is the best approach to use in this case.
Spring has a @PostConstruct annotation to do exactly that. Runs once the bean has been initialized and all dependencies added.
If it has to be run once immediately after application is initialized, I would simply start it from the init method of a singleton bean. Spring ensures that at be time it will be run all dependant beans will have been initialized.
For example, assuming a Java annotation Spring configuration you could use something like:
@Bean(init_method="init")
class TaskLauncher {
@Autowired DependantBeanClass dependant Bean;
...
public void init() {
// execute or start the task, eventually using the autowired dependant beans
...
}
}
When the context is refreshed, Spring autowire everything, initializes the dependant beans and then will call once the init
method of the TaskLauncher
bean.
No need for @Scheduler nor Quartz if you only need to start something at Spring initialization time
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