Spring Boot - Best way to start a background thread on deployment

前端 未结 2 1857
轮回少年
轮回少年 2020-12-15 01:14

I have a Spring Boot application deployed in Tomcat 8. When the application starts I want to start a worker Thread in the background that Spring Autowires with some depende

相关标签:
2条回答
  • 2020-12-15 02:01

    The main method is not called when deploying the application to a non-embedded application server. The simplest way to start a thread is to do it from the beans constructor. Also a good idea to clean up the thread when the context is closed, for example:

    @Component
    class EventSubscriber implements DisposableBean, Runnable {
    
        private Thread thread;
        private volatile boolean someCondition;
    
        EventSubscriber(){
            this.thread = new Thread(this);
            this.thread.start();
        }
    
        @Override
        public void run(){
            while(someCondition){
                doStuff();
            }
        }
    
        @Override
        public void destroy(){
            someCondition = false;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-15 02:10

    You could have a bean which impelements ApplicationListener<ContextRefreshedEvent> It's onApplicationEvent will be called just start your thread there if it hasn't been started already. I think you want the ApplicationReadyEvent by the way.

    Edit How to add a hook to the application context initialization event?

    @Component
    public class FooBar implements ApplicationListener<ContextRefreshedEvent> {
    
        Thread t = new Thread();
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            if (!t.isAlive()) {
                t.start();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题