实现计时器的最佳方法是什么?代码示例会很棒!对于这个问题,“最佳”被定义为最可靠(失火次数最少)和最精确。如果我指定 15 秒的间隔,我希望每 15 秒调用一次目标方法,而不是每 10 - 20 秒调用一次。另一方面,我不需要纳秒精度。在此示例中,该方法每 14.51 - 15.49 秒触发一次是可以接受的。
Use the class.
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read() != 'q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
The Elapsed
事件将每隔 X 毫秒引发一次,由Interval
Timer 对象上的属性。它会调用Event Handler
您指定的方法。在上面的例子中,它是OnTimedEvent
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)