2017-07-27 10 views
0

私はSpringブートアプリケーションからいくつかTimerTask秒を実行しています。 CommandLineRunner実装は以下のようなものです:すべてのタイマーが終了したら、Spring Bootアプリを終了してください

@SpringBootApplication 
public class Main implements CommandLineRunner { 

    private final Timer1 timer1; 
    private final Timer2 timer2; 

    static LocalDateTime startTime = LocalDateTime.now(); 

    public Main(Timer1 timer1, Timer2 timer2) { 
    this.timer1 = timer1; 
    this.timer2 = timer2; 
    } 

    public static void main(String[] args) { 
    SpringApplication app = new SpringApplication(Main.class); 
    app.setBannerMode(Banner.Mode.OFF); 
    app.run(args); 
    } 

    @Override 
    public void run(String... args) throws Exception { 
    Timer t1 = new Timer(); 
    Timer t2 = new Timer(); 
    int tickTime = 10000; 
    t1.scheduleAtFixedRate(this.timer1, 0, tickTime); 
    t2.scheduleAtFixedRate(this.timer2, 5000, tickTime); 
    } 

} 

首尾上記スケジュールの両方TimerTasks。しかし私のタイマーの仕事では、現在の時間をMain.startTimeと照合して、実行中の分をカウントしています。分がしきい値を超えた場合は、タスクをキャンセルします。

// Timer1.java 
@Component 
public class Timer1 extends GenericTimer { 

    @Override 
    public void run() { 
    quitIfTimedOut(); 
    } 

} 

// Timer2.java 
@Component 
public class Timer2 extends GenericTimer { 

    @Override 
    public void run() { 
    quitIfTimedOut(); 
    } 

} 

// GenericTimer.java 
public abstract class GenericTimer extends TimerTask { 

    protected void quitIfTimedOut() { 
    LocalDateTime now = LocalDateTime.now(); 
    int timeoutThreshold = 1; 
    long minutesSinceRunning = Main.startTime.until(now, ChronoUnit.MINUTES); 

    if (minutesSinceRunning >= timeoutThreshold) { 
     cancel(); 
    } 
    } 

} 

これまでのところ、指定された基準に従ってタイマータスクが正しくキャンセルされています。私の質問は、すべてのタイマーのタスクがキャンセルされた場合、メインスレッドを終了する方法ですか?

Main.javaでキャンセルするタスクを継続的に監視し、SpringApplication.close(...)に電話する必要がありますか、より便利で堅牢な方法がありますか?私はApplicationContextを注入し、アプリケーションを正常に閉じるために、次のような何かを

答えて

0

私が何をした最良の方法は、あなたが言及したようである

int exit = SpringApplication.exit(this.applicationContext); // close gracefully before exit 
System.exit(exit); 

春はすべてのDB接続などを閉じ、私は強制的にアプリケーションを終了します。

関連する問題