我遇到了一个问题,即在间隔之前触发了 Elapsed 事件。我将间隔设置为 .. 10000 毫秒,事件将在大约 4500 毫秒时触发。我知道这个特定的计时器并不太精确,但我确实知道它比它显示的要精确得多。
我已检查以确保调用此事件的计时器不超过一个。该解决方案在安装它的三台 Windows 机器中的两台上完美运行。
.net版本,clr版本等可能有问题吗?
我知道还有其他方法可以实现这一点,但我只是在寻找可能导致这仅在三分之二的服务器上工作的建议。
下面我只在服务启动时创建一次计时器..
checkTimer = new System.Timers.Timer(getSecondsLeft());
checkTimer.Elapsed += checkNowEvent;
checkTimer.AutoReset = true;
checkTimer.Enabled = true;
这是用于计算直到下一分钟的毫秒数的方法
private double getSecondsLeft()
{
DateTime now = DateTime.Now;
// Has a chance to trigger a few milliseconds before new minute. Added 50ms to interval
return ((60 - now.Second) * 1000 - now.Millisecond) + 50;
}
最后是经过的时间事件。
private void checkNowEvent(object sender, ElapsedEventArgs e)
{
try
{
// Stop timer to keep from firing this event again
checkTimer.Enabled = false;
// DOING WORK HERE
}
finally
{
// Set the interval as to tick on the start of the next minute
checkTimer.Interval = getSecondsLeft();
// Start timer again
checkTimer.Enabled = true;
}
}
我只是对此进行了更多测试,并添加了一些秒表功能,以查看间隔是否真的在它应该触发的时候触发并且看起来确实如此。但是,当我计算到下一分钟的正确毫秒数时,它的行为就好像 Timer 的这个实现比系统时钟运行得更快......如果这有任何意义的话。
这是我用来找出答案的代码。
private void checkNowEvent(object sender, ElapsedEventArgs e)
{
stopWatch.Stop();
_Log.LogDebug(stopWatch.Elapsed.ToString());
try
{
// Stop timer to keep from firing this event again
checkTimer.Enabled = false;
// DOING WORK HERE
}
catch (Exception ex)
{
// CATCHING EXCEPTIONS HERE IF ANY
}
finally
{
// Set the interval as to tick on the start of the next minute
checkTimer.Interval = getSecondsLeft();
_Log.LogDebug(checkTimer.Interval.ToString());
// Start timer again
checkTimer.Enabled = true;
stopWatch.Reset();
stopWatch.Start();
}
}