springscheduled-tasksquartz-schedulerquartz-core

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.


Solution

  • 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