簡體   English   中英

如何從Windows服務啟動計時器上的方法?

[英]How to start method on timer from windows service?

我有一個方法,可以在大約10分鍾內執行。 它本身進行得很好。 我需要每小時使用Windows服務啟動此方法(這是強制性的)。 因此,我通過一些示例(僅一個用於啟動的調用)編寫了我的服務:

partial class ServiceWSDRun : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        Thread t = new Thread(WebServiceDownload.MainProgram.Execute);
        t.Start();
    }
}

現在,當我安裝它時,它將在一個新線程中啟動我的方法,但是該線程似乎以OnStart()結尾-實際上它從我的方法開頭記錄了一些信息。 為什么停止,我該怎么辦?

我在想最后我應該有這樣的東西:

partial class ServiceWSDRun : ServiceBase
{
    System.Timers.Timer timer = null;

    protected override void OnStart(string[] args)
    {
        Thread t = new Thread(WebServiceDownload.MainProgram.Execute);
        t.Start();

        timer = new System.Timers.Timer();
        timer.Interval = 60 * 60 * 1000; // 1 hour
        timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
        timer.Enabled = true;
    }

    public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
    {
        WebServiceDownload.MainProgram.Execute();
    }

    protected override void OnStop()
    {
        timer.Enabled = false;
    }
}

我該如何運作? 請記住,該方法大約需要10分鍾才能執行。

您應該使用System.Threading.Timer而不是System.Timers.Timer。

這是此的參考:

https://msdn.microsoft.com/en-us/library/system.threading.timer(v=vs.110).aspx

另外,關於同一主題的另一個主題:

System.Timers.Timer與System.Threading.Timer

您應該鎖定執行,避免在第一個執行完成之前執行第二個執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM