2017-07-13 10 views
1

私はspring-bootサーバーアプリケーションを持っています。機能の一つで、私はいくつかの予定のスレッドを実行します。アプリケーションの起動後にクラス内でメソッドを実行する

private ScheduledExecutorService pool = Executors.newScheduledThreadPool(10); 
    private threadsNumber = 10; 

    @PostConstruct 
    void startThreads() { 
      for (int i = 1; i <= threadsNumber; ++i){ 
       pool.scheduleAtFixedRate(new Runnable() { 
        @Override 
        public void run() { 
          //set Thread Local in depends on i 
          // do some other stuff 

         } 
        } 
       }, 0, 10, TimeUnit.SECONDS); 
      } 
     } 
    } 
} 

質問です:春ブートに注釈@PostConstructを回避し、結果を取得する方法

+0

は、コンストラクタでコードを実行します。 springがBeanを起動し、スケジューラを実行できます – pandaadb

答えて

0

を「アプリを起動した後に一度だけ実行します」 Springは、ApplicationListener<ContextRefreshedEvent>インターフェイスとそのフックを提供します(onApplicationEvent(ContextRefreshedEvent event))。例えば

public abstract class MyServiceCreationListener implements ApplicationListener<ContextRefreshedEvent> { 

    @Override 
    public void onApplicationEvent(ContextRefreshedEvent event) { 
     // do something on container startup 
    } 
} 
関連する問題