System.Timers.Timer在Azure辅助角色中徘徊

发布于 2024-12-04 17:07:37 字数 741 浏览 1 评论 0原文

我有一个包含 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                                            
    }
}

问题:

  1. 可能是什么原因造成的?
  2. 将 Thread.Sleep(sleeptimeinMS) 调用添加到 while(true){} 循环会改善 这是通过防止主线程一直忙(以 允许计时器线程以某种方式更自由地履行其职责?)?
  3. 我应该尝试将角色重新同步到某些人,这是正确的答案吗? 外部时钟周期性地?
  4. 有什么完全不同的方法来实现这一点吗?

提前感谢您抽出时间,

亚历克斯

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:

  1. What might be causing this?
  2. 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?)?
  3. Is the right answer that I should try to resync the roles to some
    external clock periodically?
  4. Any radically different ways to implement this?

Thanks in advance for your time,

Alex

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

思念满溢 2024-12-11 17:07:38

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文