簡體   English   中英

在Windows服務中運行計時器

[英]Run timer in windows service

我有一個Windows服務,它正在檢查給定路徑中是​​否創建了新文件。 為此,我制作了一個計時器,該計時器每秒鍾檢查一次目錄中新文件的創建。 我通過Log4net庫將Windows服務的所有操作保存在日志中。 我啟動服務時出現問題。 當我想啟動計時器時,它停止了。

那就是我的窗口服務類:

public partial class WindowsService : ServiceBase
{

    private aTimer timer;
    private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public WindowsService()
    {            
        InitializeComponent();
    }

    public void OnDebug()
    {
        OnStart(null);
    }

    private void StartTimer()
    {
        timer.StartTimer();
    }

    private void StopTimer()
    {
        timer.CloseTimer();
    }


    protected override void OnStart(string[] args)
    {
        logger.Debug("Service is started.");
        logger.Debug("-----------------------------------------------------------");
        this.StartTimer();


    }

    protected override void OnStop()
    {
        this.StopTimer();         
        logger.Debug("-----------------------------------------------------------");
        logger.Debug("Service is stopped.");

    }
}

多數民眾贊成在我的計時器類:

public class aTimer
{
    private System.Timers.Timer timer;
    private bool timerTaskSuccess;

    private static readonly String path = "C:\\path\\";
    private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public aTimer() { }

    public void StartTimer()
    {
        try
        {
            timer = new System.Timers.Timer(1000);

            timer.Elapsed += OnTimedEvent;
            timer.AutoReset = true;
            timer.Enabled = true;
            timer.Start();

            timerTaskSuccess = false;
        }
        catch (Exception ex)
        {
            logger.ErrorFormat("Error ocurred while starting the timer: '{0}'", ex);
        }

        Watcher watcher = new Watcher();
        watcher.CreateWatcher(path);
    }

    private void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        try
        {
            logger.InfoFormat("The Elapsed event was raised at '{0:HH:mm:ss}'", e.SignalTime);
            timerTaskSuccess = true;
        }
        catch (Exception ex)
        {
            logger.ErrorFormat("Error ocurred while catching event the timer: '{0}'", ex);
            timerTaskSuccess = false;
        }
        finally
        {
            if (timerTaskSuccess)
            {
                timer.Start();
            }
        }

    }


    public void CloseTimer()
    {
        try
        {
            timer.Enabled = false;
            timer.Stop();
            timer.Dispose();
            timer = null;

            timerTaskSuccess = true;
        }
        catch (Exception ex)
        {
            logger.ErrorFormat("Error ocurred while stopping the timer: '{0}'", ex);
        }

    }
}

任何人都可以幫助我。 我在控制台應用程序中測試了邏輯代碼,並且工作正常。 問題出在哪里? 謝謝!

聲明成員

private aTimer timer;

但實際上您從未真正調用過構造函數 ,例如:

timer = new aTimer();

因此,在WindowsService.StartTimer()方法中,您將獲得NullReferenceException 將以上行添加到服務的構造函數中,就可以了。

有兩種主要方法可以調試Windows服務。 一種更為嚴格,但需要更長的時間。 另一個是快速而簡單的。

  1. 在Visual Studio中進行調試。 包裝所有代碼,使其可以作為Windows服務或控制台應用程序啟動。 有很多方法可以做到這一點,但是我所見過的最好的方法是在應用程序的main方法中涉及條件編譯。 在Debug中運行時,僅執行主類。 在Release中運行時,服務模式會啟動,服務會正常啟動。

  2. 調試已安裝的Windows服務。 在您的應用程序中放置大量睡眠/等待時間,安裝后只需使用Visual Studio附加到它即可。 如果您睡眠30秒鍾,應該有足夠的時間返回Visual Studio,請轉至附加菜單,找到應用程序並附加。 執行將在您的斷點處停止。

暫無
暫無

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

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