2009-07-29 55 views
3

我在寫一個需要全天候運行的Windows服務。這是一個非常簡單的服務,它監視文件被放入並處理這些文件的目錄。如果拋出未處理的異常,我需要重新啓動服務。當拋出異常時重新啓動服務

有沒有辦法使服務在發生未處理的異常時自行重啓?

回答

2

服務小程序有許多不同的恢復特性:

Services Recovery

它可以在第一,第二和隨後的故障不同的操作:

  • 重新啓動該服務後,可配置延遲
  • 運行程序(通過命令行參數,可能包括故障計數)
  • 重新啓動計算機(可配置的延遲後,並與特定的消息被髮送)

運行應該能看在事件日誌中看到失敗(特別是如果你登錄的話)的原因,程序,因此如果該異常是不可恢復的異常,則應該能夠禁用該服務。

而且,當然,在此期間,服務應記錄正在發生的事情,這應該使任何管理工具能夠通知操作人員發生了什麼。

我同意你可能不應該配置「第三個和後續」爲「重新啓動服務」,或者你可以結束循環。

2

您是否嘗試過使用服務項的恢復選項卡 - 可以設置故障規則,包括「重新啓動服務」 - 默認情況下,這是對「不採取行動」

+0

我沒有意識到,這是甚至可用。謝謝! – 2009-07-29 16:37:03

0

在亞軍包裝你的服務代碼它可以捕獲任何錯誤並重新啓動服務。

0

最好的方法是圍繞服務中的方法包裝Try/Catch塊,您可以通過負責來引發異常。

但是,可能會引發嚴重的異常,導致服務立即停止。不要忽視這些!在這些情況下,處理異常,記錄它,發送電子郵件然後重新拋出它。這樣你會被告知異常已經發生,並且會知道出了什麼問題。然後,您可以修復問題並手動重新啓動該服務。

只是忽略它可能會導致您的系統出現重大故障,您不知道。如果服務停止然後重啓然後停止無限,它也可能在CPU/RAM上非常昂貴。

1

這是可以通過編程方式完成,如果你想,這段代碼不是由我寫的。我將鏈接發佈到包含源代碼/二進制文件的作者CodeProject頁面。在鏈接下面,我已經解釋了我是如何實現作者代碼的。

http://www.codeproject.com/KB/install/sercviceinstallerext.aspx

  1. 添加到DLL的引用。

  2. 打開ProjectInstaller.Designer.vb在記事本
    在InitializeComponent子
    CHANGE
    Me.ServiceProcessInstaller1 = New System.ServiceProcess.ServiceProcessInstaller
    Me.ServiceInstaller1 = New System.ServiceProcess.ServiceInstaller
    TO
    Me.ServiceProcessInstaller1 = New System.ServiceProcess.ServiceProcessInstaller
    Me.ServiceInstaller1 = New Verifide.ServiceUtils.ServiceInstallerEx

  3. 隨着朋友聲明在ProjectInstaller。 Designer.vb
    CHANGE
    Friend WithEvents ServiceProcessInstaller1 As System.ServiceProcess.ServiceProcessInstaller
    Friend WithEvents ServiceInstaller1 As System.ServiceProcess.ServiceInstaller
    TO
    Friend WithEvents ServiceProcessInstaller1 As System.ServiceProcess.ServiceProcessInstaller
    Friend WithEvents ServiceInstaller1 As Verifide.ServiceUtils.ServiceInstallerEx

  4. CHANGE
    Me.Installers.AddRange(New System.Configuration.Install.Installer() {Me.ServiceProcessInstaller1, Me.ServiceInstaller1})
    TO
    Me.Installers.AddRange(New System.Configuration.Install.Installer() {Me.ServiceInstaller1, Me.ServiceProcessInstaller1})

  5. 導入命名空間在ProjectInstaller.vb

  6. 在ProjectInstaller.vb在公用Sub新功能初始化組件函數被調用
    之後添加
    'Set Reset Time Count - This Is 4 Days Before Count Is Reset
    ServiceInstaller1.FailCountResetTime = 60 * 60 * 24 * 4
    'ServiceInstaller1.FailRebootMsg = "Houston! We have a problem"

    'Add Failure Actions
    ServiceInstaller1.FailureActions.Add(New FailureAction(RecoverAction.Restart, 60000))
    ServiceInstaller1.FailureActions.Add(New FailureAction(RecoverAction.Restart, 60000))
    ServiceInstaller1.FailureActions.Add(New FailureAction(RecoverAction.None, 3000))

    ServiceInstaller1.StartOnInstall = True

  7. 編譯安裝程序並安裝。 Voila

0

正如「John Saunders」和「thegecko」所建議的那樣,您可以監視服務並在服務失敗時重新啓動服務。內置的Windows服務恢復功能將爲您帶來很長的路要走,但是如果您發現需要更高級的功能(例如CPU佔用和掛起檢測),那麼請查看Service Protector。它旨在讓您的重要Windows服務全天候運行。

祝你好運!

相關問題