.NET, event every minute (on the minute). Is a timer the best option?

后端 未结 14 2087
-上瘾入骨i
-上瘾入骨i 2020-11-27 03:02

I want to do stuff every minute on the minute (by the clock) in a windows forms app using c#. I\'m just wondering whats the best way to go about it ?

I could use a t

相关标签:
14条回答
  • 2020-11-27 03:56

    Use a timer set to run every second (or millisecond, whatever your accuracy threshold is), and then code the method to run your functionality if and only if the current time is within that threshold past the "on the minute" point.

    0 讨论(0)
  • 2020-11-27 03:59

    You could set up two timers. An initial short interval timer (perhaps to fire every second, but dependent on how presice the second timer must fire on the minute).

    You would fire the short interval timer only until the desired start time of the main interval timer is reached. Once the initial time is reached, the second main interval timer can be activated, and the short interval timer can be deactivated.

    void StartTimer()
    {
    
      shortIntervalTimer.Interval = 1000;
      mainIntervalTimer.Interval = 60000; 
    
      shortIntervalTimer.Tick += 
        new System.EventHandler(this.shortIntervalTimer_Tick);
      mainIntervalTimer.Tick += 
        new System.EventHandler(mainIntervalTimer_Tick);
    
      shortIntervalTimer.Start();
    
    }
    
    private void shortIntervalTimer_Tick(object sender, System.EventArgs e)
    {
      if (DateTime.Now.Second == 0)
        {
          mainIntervalTimer.Start();
          shortIntervalTimer.Stop();
        }
    }
    
    private void mainIntervalTimer_Tick(object sender, System.EventArgs e)
    {
      // do what you need here //
    }
    
    0 讨论(0)
提交回复
热议问题