简体   繁体   English

C#中Windows服务启动时的调用方法

[英]Calling method at the start of windows service in c#

Please look at this piece of code 请看这段代码

 public partial class TestService : ServiceBase
 {
     private static System.Timers.Timer aTimer;

     protected override void OnStart(string[] args)
     {
        aTimer = new Timer(10000 * 6 * 5); //  5 minutes interval
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Enabled = true;
     }

     private void OnTimedEvent(object source, ElapsedEventArgs e)
     {
      ......
     }
 }

When I start this service at say 4:00 pm, the first time OnTimedEvent is called is at 4:05 pm, then 4:10 pm and so on. 当我在下午4:00启动此服务时,首次调用OnTimedEvent的时间是下午4:05,然后是下午4:10,依此类推。 I would like the OnTimedEvent to be called at 4:00 pm as soon as I start the service. 我希望在启动服务后的4:00 pm调用OnTimedEvent。 Is there anything I am missing here? 我在这里想念什么吗?

您可以在OnStart中调用该事件

OnTimedEvent(this, null)

Use a System.Threading.Timer rather than a System.Timers.Timer . 使用System.Threading.Timer而不是System.Timers.Timer

It has a constructor overload that in addition to specifying the interval allows you choose the start delay, which can be set to 0 to fire immediately. 它具有构造函数重载,除了指定间隔之外,您还可以选择启动延迟,可以将其设置为0以立即触发。

For a Comparison of the timer classes, see Windows.Forms.Timer OR System.Threading.Timer (specifically ' Initial timer event schedulable? ') 有关计时器类的比较,请参见Windows.Forms.Timer或System.Threading.Timer (特别是“可计划的初始计时器事件? ”)

System.Timers.Timer starts counting down from 5 minutes and then the event is triggered. System.Timers.Timer从5分钟开始倒计时,然后触发该事件。 So it won't be able to trigger and run the code till the timer reaches 0. 因此,直到计时器达到0时,它才能触发和运行代码。

The code may be run before the event listener is enabled this way shown below: 如下所示,可以在启用事件侦听器之前运行代码:

 public partial class TestService : ServiceBase { private static System.Timers.Timer aTimer; protected override void OnStart(string[] args) { aTimer = new Timer(10000 * 6 * 5); // 5 minutes interval aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); foo(); aTimer.Enabled = true; } private void OnTimedEvent(object source, ElapsedEventArgs e) { foo(); } private void foo(){ ..... } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM