How to use the .NET Timer class to trigger an event at a specific time?

前端 未结 9 1683

I would like to have an event triggered in my app which runs continuously during the day at a certain time, say at 4:00pm. I thought about running the timer every second and

9条回答
  •  粉色の甜心
    2020-12-01 00:29

    How about something like this, using the System.Threading.Timer class?

    var t = new Timer(TimerCallback);
    
    // Figure how much time until 4:00
    DateTime now = DateTime.Now;
    DateTime fourOClock = DateTime.Today.AddHours(16.0);
    
    // If it's already past 4:00, wait until 4:00 tomorrow    
    if (now > fourOClock)
    {
        fourOClock = fourOClock.AddDays(1.0);
    }
    
    int msUntilFour = (int)((fourOClock - now).TotalMilliseconds);
    
    // Set the timer to elapse only once, at 4:00.
    t.Change(msUntilFour, Timeout.Infinite);
    

    Note that if you use a System.Threading.Timer, the callback specified by TimerCallback will be executed on a thread pool (non-UI) thread—so if you're planning on doing something with your UI at 4:00, you'll have to marshal the code appropriately (e.g., using Control.Invoke in a Windows Forms app, or Dispatcher.Invoke in a WPF app).

提交回复
热议问题