代码之家  ›  专栏  ›  技术社区  ›  Scott Ferguson

间隔几个月的计时器

  •  2
  • Scott Ferguson  · 技术社区  · 14 年前

    我有一个Windows服务处理由System.Timers.Timer触发的事件。 我想把计时器的时间间隔设为3个月。

    System.Timers.Timer的Interval属性是Int32(以毫秒为单位),Int32.MaxValue小于3个月(以毫秒为单位)。

    我该怎么办?

    5 回复  |  直到 7 年前
        1
  •  10
  •   James Kovacs    14 年前

        3
  •  1
  •   Javed Akram    14 年前

        int interval = 10 * 24 * 60 * 60 * 1000; // Time interval for 10 days 
        int counter = 0;
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            counter++;
            if (counter == 9) 
            {
                //do your task for 3 months
                //since counter increments 9 times at interval of 10 days
                //so 9*10=90 days i.e. nearly equal to 3 months
                counter = 0;
            }
        }
    
        4
  •  1
  •   Nyerguds    7 年前

    DateTime DateTime.Now

    Int32.MaxValue

    private Timer _timer;
    private Boolean _overflow;
    
    private void QueueNextTime(DateTime thisTime)
    {
        TimeSpan interval = this.GetNextRunTime(thisTime) - DateTime.Now;
        Int64 intervalInt = (Int64)((interval.TotalMilliseconds <= 0) ? 1 : interval.TotalMilliseconds);
        // If interval greater than Int32.MaxValue, set the boolean to skip the next run. The interval will be topped at Int32.MaxValue.
        // The TimerElapsed function will call this function again anyway, so no need to store any information on how much is left.
        // It'll just repeat until the overflow status is 'false'.
        this._overflow = intervalInt > Int32.MaxValue;
        this._timer.Interval = Math.Min(intervalInt, Int32.MaxValue);
        this._timer.Start();
    }
    
    // The function linked to _timer.Elapsed
    private void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        this._timer.Stop();
        if (this._overflow)
        {
            QueueNextTime(e.SignalTime);
            return;
        }
    
        // Execute tasks
        // ...
        // ...
    
        // schedule next execution
        QueueNextTime(e.SignalTime);
    }
    

        5
  •  0
  •   dexter    14 年前