2011-06-23 83 views
5

這是我第一次使用windows服務,而且我正在學習。 我正在使用VS 2010,Windows 7創建一個將有計時器的Windows服務。我用Google搜索和瀏覽這個網站,以及Use of Timer in Windows ServiceBest Timer for using in a Windows service但我仍然很困惑,在哪裏在窗口服務組件定時器在VS 2010中添加一個System.Threading.Timer到一個windows服務

我在service1.cs類的OnStart方法,並調用OnStop方法的代碼
我在哪裏編碼計時器執行功能(不啓動Windows服務)?

+0

你實際上是在談論* *啓動該服務或定期*您服務中執行某些功能*? –

+0

在服務中定期執行該功能 – user788487

回答

6

下面是如何做到這一點的一個例子。它每10秒嚮應用程序日誌寫入一條消息(如在事件查看器中所見),直到服務停止。在你的情況下,把你的週期性邏輯放在OnElapsedEvent()方法中。

private System.Timers.Timer _timer = new System.Timers.Timer(); 

protected override void OnStart(string[] args) 
{ 
    _timer.AutoReset = true; 
    _timer.Interval = 10000; // 10 seconds 
    _timer.Elapsed += OnElapsedEvent; 
    _timer.Start(); 
} 

protected override void OnStop() 
{ 
    _timer.Stop(); 
} 

private void OnElapsedEvent(object sender, ElapsedEventArgs e) 
{ 
    // Write an entry to the Application log in the Event Viewer. 
    EventLog.WriteEntry("The service timer's Elapsed event was triggered."); 
} 

我在這裏有幾個詳細的答案,可能對您開始使用Windows服務有幫助。

+0

非常感謝馬特。那就是我需要的。 – user788487

4

使用計劃任務運行一個小控制檯應用程序或類似程序會更容易,而不是處理Windows Service可帶來的各種細微差別?

如果不是,您可能需要閱讀編寫windows服務(如this c# articlethis VB Article)的正常文章。一旦你看到一個普通的服務如何運行(一個不使用定時器的服務),你應該知道在計時器代碼中添加的位置。

希望有幫助嗎?

+0

運行數小時(本例爲9小時)的計劃任務似乎被縮短了。不確定代碼中的錯誤或Task Scheduler的問題。但這種替代方法將會有所幫助。我在這裏工作的地方對任何一方都很好。但他們可能是一個決定性因素。 – TamusJRoyce

+0

@TamusJRoyce 4歲的線程;讓我知道你是否有任何問題(或更好的,在Twitter上相同的用戶名)。祝你好運。 – Smudge202

相關問題