代码之家  ›  专栏  ›  技术社区  ›  marc_s

Windows服务中的计时器-不起作用?

  •  1
  • marc_s  · 技术社区  · 15 年前

    我有一个c中的windows nt服务,它基本上每x秒唤醒一次,检查是否需要发送任何邮件通知,然后返回休眠状态。

    看起来像这样 Timer 班级来自 System.Threading 命名空间):

    public partial class MyService : ServiceBase
    {
        private Timer _timer;
        private int _timeIntervalBetweenRuns = 10000;
    
        public MyService()
        {
            InitializeComponent();
        }
    
        protected override void OnStart(string[] args)
        {
            // when NT Service starts - create timer to wake up every 10 seconds
            _timer = new Timer(OnTimer, null, _timeIntervalBetweenRuns, Timeout.Infinite);
        }
    
        protected override void OnStop()
        {
            // on stop - stop timer by freeing it
            _timer = null;
        }
    
        private void OnTimer(object state)
        {
            // when the timer fires, e.g. when 10 seconds are over 
            // stop the timer from firing again by freeing it
            _timer = null;
    
            // check for mail and sent out notifications, if required - works just fine
            MailHandler handler = new MailHandler();
            handler.CheckAndSendMail();
    
            // once done, re-enable the timer by creating it from scratch
            _timer = new Timer(OnTimer, null, _timeIntervalBetweenRuns, _timeIntervalBetweenRuns);
        }
    }
    

    发送邮件和所有的工作都很好,而且服务也每10秒唤醒一次(实际上,这是配置文件中的一个设置,对于本例来说是简化的)。

    然而,有时,服务似乎醒得太快了……

    2010-04-09 22:50:16.390
    2010-04-09 22:50:26.460
    2010-04-09 22:50:36.483
    
    2010-04-09 22:50:46.500
    2010-04-09 22:50:46.537  ** why again after just 37 milliseconds...... ??
    
    2010-04-09 22:50:56.507
    

    工作正常到22:50:45.500-为什么它只在37毫秒后记录另一个条目??

    在这里,似乎完全不正常…似乎每过10秒就醒来两次甚至三次…

    2010-04-09 22:51:16.527
    
    2010-04-09 22:51:26.537
    2010-04-09 22:51:26.537
    
    2010-04-09 22:51:36.543
    2010-04-09 22:51:36.543
    
    2010-04-09 22:51:46.553
    2010-04-09 22:51:46.553
    
    2010-04-09 22:51:56.577
    2010-04-09 22:51:56.577
    
    2010-04-09 22:52:06.590
    2010-04-09 22:52:06.590
    
    2010-04-09 22:52:06.600
    2010-04-09 22:52:06.600
    

    你知道为什么吗??这不是一个大问题,但我担心如果我配置的时间间隔(10秒,30秒-随便什么)越来越被忽略,服务运行的时间就越长,服务器可能会负载过大。

    我的服务代码中是否遗漏了一些非常基本的内容??我最后是不是有多个计时器,还是什么??我好像不太明白……我选错时间了吗( System.Threading.Timer )?.net中至少有3个计时器类-为什么??)

    3 回复  |  直到 15 年前
        1
  •  2
  •   marc_s    15 年前

    实际上,问题似乎是我选错了计时器类。

    System.Threading.Timer ,我在最初的问题中解释过这些问题。

    当我切换到 System.Timers.Timer ,所有这些问题都消失了。

    所以这仍然回避了一个问题:为什么地球上至少有三种 Timer .NET框架中的类,它们之间的(细微的)区别是什么?

        2
  •  1
  •   jake.stateresa    15 年前

    从上面的代码来看,不明显的是,您得到了多个计时器。但在我看来可能是这样。因为system.threading.timer实现了IDisposable,所以应该改为调用dispose方法,而不是使变量为空。

    MSDN说…

    当不再需要计时器时,使用 释放 计时器持有的资源。

        3
  •  0
  •   Paulo Santos    15 年前

    这可能是因为消息管道。

    有时会发送计时器消息,但处理速度不够快,因此它们会按顺序堆叠和处理。

    推荐文章