System.Timers.Timer在Azure辅助角色中徘徊
我有一个包含 n 个(当前 n = 2)个实例的 Azure 辅助角色。每个实例的主线程上都有一个 System.Timers.Timer,每 20 秒执行一次,产生一些工作进程。当角色实例最初启动时,它们通过内部端点同步自身,以便计时器同时启动(这是有效的)。
即使在一天的过程中,这两个具有相同间隔的计时器也往往会出现漂移——其中一个最终会比以前提前几秒钟开始,而另一个可能会朝相同的方向发展,或者更糟糕的是另一个。
我的运行方法基本上如下:
public override void Run()
{
while (true)
{
GC.KeepAlive(this.LogTimer); // make sure garbage collection never touches the timer
}
}
问题:
- 可能是什么原因造成的?
- 将 Thread.Sleep(sleeptimeinMS) 调用添加到 while(true){} 循环会改善 这是通过防止主线程一直忙(以 允许计时器线程以某种方式更自由地履行其职责?)?
- 我应该尝试将角色重新同步到某些人,这是正确的答案吗? 外部时钟周期性地?
- 有什么完全不同的方法来实现这一点吗?
提前感谢您抽出时间,
亚历克斯
I have an Azure Worker Role with n (currently n = 2) instances. Each of these instances has a System.Timers.Timer on its main thread that executes every 20 seconds, spawning some work processes. When the role instances boot up initially, they synchronize themselves via internal endpoints so that the timers start at the same time (this works).
Over the course of even a day, these two timers with the same interval tend to wander - one will end up starting several seconds before it used to, and the other may go the same direction or, worse, the other.
My run method is basically the following:
public override void Run()
{
while (true)
{
GC.KeepAlive(this.LogTimer); // make sure garbage collection never touches the timer
}
}
Questions:
- What might be causing this?
- Would adding a Thread.Sleep(sleeptimeinMS) call to the while(true){} loop improve
this by preventing the main thread from being busy all the time (to
allow the timer thread to be somehow more free to do its duty?)? - Is the right answer that I should try to resync the roles to some
external clock periodically? - Any radically different ways to implement this?
Thanks in advance for your time,
Alex
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
System.Timers.Timer 并不是 100% 准确,它受到操作系统中线程调度的限制。这是有道理的,两个独立的服务器各自运行一个计时器,最终会失去同步。
A System.Timers.Timer is not 100% accurate, it is limited by the thread scheduling in the OS. It makes good sense that two separate servers each running a Timer, eventually will get out of synch.