Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring, Run task once when application started

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:

  1. 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; } }

  2. Using Quartz. But I have not used before.

Please, tell me what is the best approach to use in this case.

like image 852
I. Domshchikov Avatar asked Aug 10 '16 06:08

I. Domshchikov


2 Answers

Spring has a @PostConstruct annotation to do exactly that. Runs once the bean has been initialized and all dependencies added.

like image 52
Shawn Clark Avatar answered Sep 21 '22 15:09

Shawn Clark


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

like image 37
Serge Ballesta Avatar answered Sep 18 '22 15:09

Serge Ballesta