How to set timer to execute at specific time in c#

后端 未结 4 2247
南旧
南旧 2020-12-09 18:22

I have a requirement where i need to execute timer at 00:01:00 A.M every day...But i am not getting how to achieve this ..If i am taking Systems time,it can be in different

4条回答
  •  盖世英雄少女心
    2020-12-09 18:51

    If you want to start a timer at exactly 00:01:00am do some processing time and then restart the timer you just need to calculate the difference between Now and the next 00:01:00am time slot such as.

    static Timer timer;
    static void Main(string[] args)
    {
        setup_Timer();
    }
    
    static void setup_Timer()
    {
        DateTime nowTime = DateTime.Now;
        DateTime oneAmTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 0, 1, 0, 0);
        if (nowTime > oneAmTime)
            oneAmTime = oneAmTime.AddDays(1);
    
        double tickTime = (oneAmTime - nowTime).TotalMilliseconds;
        timer = new Timer(tickTime);
        timer.Elapsed += timer_Elapsed;
        timer.Start();
    }
    
    static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        timer.Stop();
        //process code..
        setup_Timer();
    }
    

提交回复
热议问题