C# 计时器每 X 秒触发一次,但与实时保持同步(即没有漂移)
C# 中是否有一个 .NET 计时器可以确保事件之间没有“漂移”?也就是说,如果您将计时器设置为每 X 秒关闭一次,那么在运行几天后它不会漂移,即确保一天中 X 秒事件的接近数量与应有的数量保持同步?
如果没有,是否有一个众所周知的代码示例可以在 C# 中包装 Timer 函数来执行此操作?
Is there a .NET Timer available in C# that can ensure there is no "drift" in between events? That is, if you set the timer to go off every X seconds, that after days of operating it won't drift, i.e. to ensure that approach number of X seconds events in a day remains in synch with what it should be?
If not, is there a well known code example that would wrap a Timer function in C# to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设你已经尝试过一些东西,并且它会发生变化。
如果您希望从一小时(5,10,15,20..)开始每 5 秒触发一次,您可以将计时器设置为触发一次,然后在回调中将计时器重置为在 DateTime.Now + 触发到下一个 5 秒间隔的秒数。
只要您的时钟正确,这就可以防止任何漂移。
像这样的东西
I'm assuming you have tried something already, and that it drifts.
If you want something to fire at say every 5 seconds from the hour (5,10,15,20..), you could set your timer to fire once, then in your callback, reset the timer to fire at DateTime.Now + number of seconds to the next 5 second interval.
This would prevent any drifting as long as your clock is correct.
Something like this
抱歉,只给您提供了 quartz.net 的链接,但这是一个完全合格的、经过测试的企业, ...图书馆...你不需要重新发明轮子:)
如果你担心开销,你对开销的定义是什么?是文件大小(二进制文件大约 0.5mb)还是逻辑开销。
对于逻辑部分来说:我认为实现他们的 IJob 接口可以很好地强制消费者使用更好的代码。我不是内联方法的大朋友(只是作为一个例子,因为你可能会在计时器流逝时触发它们的指针) - 类会给你更多的可能性,并再次强制更好的 oop,领域设计,..但是
:用quartz.net 做
Console.WriteLine(...)
就有点矫枉过正了...:)sorry for only giving you a link to quartz.net, but this is a fully qualified, enterprise, tested, ... library ... you don't need to reinvent the wheel :)
if you worry about overhead, what is your definition for overhead? is it the file-size (binaries are about 0,5mb) or the overhead in the logic.
well for the logic-part: i think that implementing their
IJob
-interface does a good job to force better code of the consumer. i'm not that big friend of inline-methods (just as an example, as you might fire their pointers on timer elapse) - classes would give you much more possibilities, and once again, force better oop, domain-design, ...but: doing
Console.WriteLine(...)
with quartz.net would be overkill ... :)