後台批次處理程式(Spring + iBatis),需 7×24 小時無人值守運行。網路抖動、資料庫重啟、配置變更等暫時性故障不得導致進程退出,故障排除後需自動恢復處理。
public static void main(String[] args) {
while (true) {
try {
// 1. 獲取/重建 Spring 容器
ApplicationContext ctx = ApplicationContextUtil.getApplicationContext();
// 2. 取得核心任務 Bean
IssuePlan issuePlan = (IssuePlan) ctx.getBean("issuePlan");
// 3. 執行任務(內部含 while(true) 迴圈,正常不退出)
issuePlan.execute();
} catch (Throwable e) { // 捕獲 Error 含 OOM、StackOverflow 等嚴重錯誤
log.error("網路視頻節目分發程式啟動發生嚴重錯誤!", e);
// 4. 等待冷卻後重試
try { Thread.sleep(PAUSE_TIMESPAN * 1000L); }
catch (InterruptedException ignored) {}
}
}
}
| 環節 | 作用 | 注意事項 |
|---|---|---|
while(true) 外層迴圈 | 進程守護,確保主線程永不結束 | 需配合 nohup、& 後台運行 |
重新獲取 ApplicationContext | 故障後重建 Spring 容器,刷新資料庫連線池、配置屬性 | 舊容器需正確關閉(註冊 shutdown hook)避免資源洩漏 |
issuePlan.execute() 內部迴圈 | 核心業務邏輯,正常情況無限運行 | 僅在「嚴重錯誤」拋出異常時退出,觸發外層重試 |
捕獲 Throwable | 攔截 Exception 之外的 Error(如 OOM),最後防線 | 謹慎使用,避免掩蓋應快速失效的程式錯誤 |
Thread.sleep 退避 | 避免故障高頻重試佔滿 CPU/日誌 | 可引入指數退避策略 |
Runtime.getRuntime().addShutdownHook() 關閉資源、持久化狀態。