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

前端 未结 9 1694

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:34

    You can use Task Sceduler on windows See daily trigger example for detail.

    or use bellow code if you want wrote it yourself:

    public void InitTimer()
    {
        DateTime time = DateTime.Now;
        int second = time.Second;
        int minute = time.Minute;
        if (second != 0)
        {
            minute = minute > 0 ? minute-- : 59;
        }
    
        if (minute == 0 && second == 0)
        {
            // DoAction: in this function also set your timer interval to 24 hours
        }
        else
        {
            TimeSpan span = //new daily timespan, previous code was hourly: new TimeSpan(0, 60 - minute, 60 - second);
            timer.Interval = (int) span.TotalMilliseconds - 100; 
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }
    }
    
    void timer_Tick(object sender, EventArgs e)
    {
        timer.Interval = ...; // 24 hours
        // DoAction
    }
    

提交回复
热议问题