将System.Threading.Timer添加到VS 2010中的Windows服务

use*_*487 5 windows-services timer c#-4.0

这是我第一次使用Windows服务,我正在学习.我正在使用VS 2010,Windows 7来创建一个具有计时器的Windows服务.我用Google搜索和浏览这个网站,以及在Windows服务使用定时器,最佳定时器使用Windows服务,但我仍然很困惑,在哪里在窗口服务组件的定时器代码

我在service1.cs类中有一个OnStart方法和OnStop方法
我在哪里编写定时器来执行该函数(不启动Windows服务)?

Mat*_*vis 6

以下是如何执行此操作的示例.它每隔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.");
}
Run Code Online (Sandbox Code Playgroud)

我在这里得到了一些详细的答案,在你开始使用Windows服务时可能会有所帮助.