【问题标题】:Timer on windows service doesn't work on the serverWindows 服务上的计时器在服务器上不起作用
【发布时间】:2015-07-06 08:51:10
【问题描述】:

我有一个使用计时器的 Windows 服务。计时器每隔几秒钟工作一次,并检查数据库中的一些更改,然后如果有任何更改,Windows 服务会执行操作。

我做了所有事情,在我的机器上进行了繁重的测试,在我的机器上,windows 服务运行良好。

当我在服务器上部署时,Windows 服务会在我 start Windows 服务时检查数据库更改,但它不会继续检查数据库中的任何更改。我不知道问题所在,我已经连续三天在这里呆了,我检查了所有内容。

在我的机器上我使用框架 32 进行部署,在服务器上我也使用框架 32 进行部署。

我也尝试使用framework 64在服务器上部署,但还是同样的问题。

我为任何失败做了一个日志,根本没有错误日志。

您能告诉我问题可能出在哪里吗?

我用这样的计时器运行 Windows 服务:

private System.Timers.Timer timer;

public ServiceStatus()
{
    InitializeComponent();

}

protected override void OnStart(string[] args)
{
    try
    {
        this.timer = new System.Timers.Timer(30000);  // 30000 milliseconds = 30 seconds
        this.timer.AutoReset = true;
        this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
        this.timer.Start();
    }
    catch (Exception ee)
    {
        this.EventLog.WriteEntry("ERROR ERROR ERROR="+ee.Message);
    }
}

protected override void OnStop()
{
    this.timer.Stop();
    this.timer = null;
}

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    new StatusHandler().check();
}

已经三天了,我无法解决,不胜感激。

【问题讨论】:

  • 在您发布的代码中,您没有处理对StatusHandler().check(); 的调用中的任何错误。因此,如果抛出异常,它将退出服务并显示您所描述的行为。当然,除非您的 check 方法确实有错误处理,否则可能会显示代码?
  • @Belogix 好的,我会上传更多代码,请稍等
  • @Belogix 我刚刚添加了 try and catch 并再次部署,如果日志中发生任何错误,我会通知您
  • @Belogix 哦哦哦我开始在日志中出现错误Object reference not set to an instance of an object.
  • 那就是问题所在! :-) 希望现在您可以找到错误并修复它。

标签: c# .net windows timer


【解决方案1】:

问题是因为 OnStart 中的 try / catch 块只会处理设置事件的代码中抛出的异常。当事件本身运行时,它不会捕获任何异常。

如果在您的 StatusHandler().check() 方法中引发异常,服务将退出并且不会记录任何内容。

因此,您需要将 try / catch 添加到您的 StatusHandler().check() 方法中,以便您可以捕获任何异常、记录它们并适当地处理它们。

【讨论】:

    猜你喜欢
    • 2017-09-30
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 2017-05-17
    • 2015-02-17
    • 1970-01-01
    相关资源
    最近更新 更多