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

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

    You can nail this with reactive extensions which will take care of lots of timer related problems for you (clock changes, app hibernation etc). Use Nuget package Rx-Main and code like this:

    Action work = () => Console.WriteLine(DateTime.Now.ToLongTimeString());
    
    Scheduler.Default.Schedule(
        // start in so many seconds
        TimeSpan.FromSeconds(60 - DateTime.Now.Second), 
        // then run every minute
        () => Scheduler.Default.SchedulePeriodic(TimeSpan.FromMinutes(1), work));               
    
    Console.WriteLine("Press return.");
    Console.ReadLine();
    

    Read here (search for "Introducing ISchedulerPeriodic") to see all the issues this is taking care of: http://blogs.msdn.com/b/rxteam/archive/2012/06/20/reactive-extensions-v2-0-release-candidate-available-now.aspx

提交回复
热议问题