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

后端 未结 14 2232
-上瘾入骨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:51

    Building on the answer from aquinas which can drift and which doesn't tick exactly on the minute just within one second of the minute:

    static System.Timers.Timer t;
    
    static void Main(string[] args)
    {
        t = new System.Timers.Timer();
        t.AutoReset = false;
        t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
        t.Interval = GetInterval();
        t.Start();
        Console.ReadLine();
    }
    
    static double GetInterval()
    {
        DateTime now = DateTime.Now;
        return ((60 - now.Second) * 1000 - now.Millisecond);
    }
    
    static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine(DateTime.Now.ToString("o"));
        t.Interval = GetInterval();
        t.Start();
    }
    

    On my box this code ticks consistently within .02s of each minute:

    2010-01-15T16:42:00.0040001-05:00
    2010-01-15T16:43:00.0014318-05:00
    2010-01-15T16:44:00.0128643-05:00
    2010-01-15T16:45:00.0132961-05:00
    

提交回复
热议问题