这是我第一次使用Windows服务,我正在学习。 我正在使用VS 2010,Windows 7来创建一个具有计时器的Windows服务。我也用Google搜索并浏览了这个网站Use of Timer in Windows Service,Best Timer for using in a Windows service但我仍然对在windows服务组件中为计时器编码的位置感到困惑
我在service1.cs类中有一个OnStart方法和OnStop方法 我会在哪里编写定时器来执行该功能(不启动Windows服务)?
答案 0 :(得分: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.");
}
我在这里得到了一些详细的答案,在您开始使用Windows服务时可能会有所帮助。
答案 1 :(得分:4)
使用计划任务运行一个小型控制台应用程序或类似程序而不是处理Windows服务可能带来的各种细微差别会更容易吗?
如果没有,您可能需要查看有关编写Windows服务的常规文章,例如this c# article或this VB Article。一旦您看到正常服务如何运行(不使用计时器的服务),您应该知道在计时器代码中添加的位置。
希望有帮助吗?