【问题标题】:Adding a System.Threading.Timer to a windows service in VS 2010在 VS 2010 中将 System.Threading.Timer 添加到 Windows 服务
【发布时间】:2011-09-21 08:00:58
【问题描述】:

这是我第一次使用 Windows 服务,我边走边学。 我正在使用 VS 2010、Windows 7 创建一个具有计时器的 Windows 服务。我已经用谷歌搜索并浏览了这个网站Use of Timer in Windows ServiceBest Timer for using in a Windows service,但我仍然对在 Windows 服务组件中为计时器编码的位置感到困惑

我在 service1.cs 类中有一个 OnStart 方法和 OnStop 方法
我将在哪里编写计时器代码以执行该功能(不启动 Windows 服务)?

【问题讨论】:

  • 您实际上是在谈论启动服务还是定期执行您的服务中的某些功能?
  • 在服务内定期执行函数

标签: c#-4.0 windows-services timer


【解决方案1】:

以下是如何执行此操作的示例。它每 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.");
}

我在 SO 这里有几个详细的答案,可能会对您开始使用 Windows 服务有所帮助。

【讨论】:

  • 非常感谢马特。这正是我所需要的。
【解决方案2】:

使用计划任务来运行一个小控制台应用程序或类似应用程序,而不是处理 Windows 服务可能带来的各种细微差别会更容易吗?

如果没有,您可能需要查看有关编写 Windows 服务的普通文章,例如 this c# articlethis VB Article。一旦你看到一个正常的服务是如何运行的(一个不使用计时器的服务),你应该知道在哪里添加计时器代码。

希望有帮助吗?

【讨论】:

  • 运行几个小时(在我的情况下为 9 小时)的计划任务似乎被缩短了。不确定是代码中的错误还是任务计划程序的问题。但这种替代方案会有所帮助。我在这里工作的 Ops 对 or 都很好。但它们可能是一个决定性因素。
  • @TamusJRoyce 4 岁线程;如果您有任何问题,请告诉我(或者更好的是,在 Twitter 上使用相同的用户名)。祝你好运。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多