运行 windows 服务中的计时器

Run timer in windows service

我有一个 windows 服务,如果创建了新文件,它会检查给定路径。为此,我制作了一个计时器,它每秒检查目录中新文件的创建。我通过 Log4net 库将 windows 服务的所有操作保存在日志中。当我启动服务时,问题就来了。当我想启动计时器时它停止了。

那是我的 window 服务 class:

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.");

    }
}

那是我的计时器 class:

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 运行 时,main class 被简单地执行。当 运行 在 Release 时,Service 模式启动,服务正常启动。

  2. 调试已安装的 Windows 服务。在您的应用程序中放置大量睡眠/等待,并在安装后使用 Visual Studio 简单地附加到它。如果您睡了 30 秒,应该有足够的时间返回 Visual Studio,转到附加菜单,找到应用程序并附加。执行将在您的断点处停止。