2012-02-22 110 views
2

我正在使用來自StdSchedulerFactory的Quartz 2.0.1調度程序。我在代碼中捕獲SchedulerException我是否需要關閉Quartz調度程序在finally塊中?

我應該關閉在finally塊中的調度:

} finally { 
    scheduler.shutdown(); 
} 

或者我應該做try塊關機?

關機方法可以拋出SchedulerException,所以看起來關機不應該在finally塊中。

回答

0

在任何情況下,您都不必在finally塊中執行它,因爲如果調度程序成功啓動,它不會拋出SchedulerException,因此如果您到達catch塊SchedulerException,這意味着調度程序從不是開始。所以,你不應該關閉從未開始的調度程序。

下面是項目homepage的示例程序。

public class QuartzTest { 

    public static void main(String[] args) { 

     try { 
      // Grab the Scheduler instance from the Factory 
      Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); 

      // and start it off 
      scheduler.start(); 

      scheduler.shutdown(); 

     } catch (SchedulerException se) { 
      se.printStackTrace(); 
     } 
    } 
} 

而且,從上面的鏈接,

一旦你獲得使用StdSchedulerFactory.getDefaultScheduler()調度,您的應用程序將不會終止,直到調用scheduler.shutdown(),因爲會有活動線程。

+0

所以,換句話說,你應該幾乎肯定會調用'從某處scheduler.shutdown()'在你的代碼,因爲如果不這樣做的應用程序可能不會停止。根據應用程序的設計,finally塊可能是也可能不是正確的地方。應用程序關閉時觸發的事件監聽器是另一個放置'scheduler.shutdown()'的地方。不停止石英(例如在Web應用程序中)可能導致嚴重的類加載器相關的內存泄漏。 – 2012-02-27 08:11:58

0

對上述答案進行抨擊時,如果除開始/關閉之外還有其他代碼,它可能仍會遇到問題。例如,如果你有這樣的事情:

public class QuartzTest { 
    public static void main(String[] args) { 

     try { 
      // Grab the Scheduler instance from the Factory 
      Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); 

      // and start it off 
      scheduler.start(); 
      System.out.println(args[5]); 
      scheduler.shutdown(); 

     } catch (SchedulerException se) { 
      se.printStackTrace(); 
     } 
    } 
} 

應用程序將永遠不會調用關機,因爲你有一個ArrayIndexOutOfBoundsException(或類似的東西)結束。有很多方法可以解決這個問題,但最簡單的方法可能是將所有中間代碼包裝在異常處理程序中並「處理」那些東西。例如: 公共類QuartzTest {

public static void main(String[] args) { 

    try { 
     // Grab the Scheduler instance from the Factory 
     Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); 

     // and start it off 
     scheduler.start(); 
     try { 
      System.out.println(args[5]); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     scheduler.shutdown(); 

    } catch (SchedulerException se) { 
     se.printStackTrace(); 
    } 
} 

}

相關問題