Windows Service to run a function at specified time

后端 未结 7 1862
一生所求
一生所求 2020-12-02 11:57

I wanted to start a Windows service to run a function everyday at specific time.

What method i should consider to implement this? Timer or using threads?

7条回答
  •  温柔的废话
    2020-12-02 12:11

    private static double scheduledHour = 10;
    private static DateTime scheduledTime;
    
    public WinService()
    {
         scheduledTime = DateTime.Today.AddHours(scheduledHour);//setting 10 am of today as scheduled time- service start date
    }
    
    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
          DateTime now = DateTime.Now;
          if (scheduledTime < DateTime.Now)
          {
             TimeSpan span = now - DateTime.Now;
             scheduledTime = scheduledTime.AddMilliseconds(span.Milliseconds).AddDays(1);// this will set scheduled time to 10 am of next day while correcting the milliseconds
             //do the scheduled task here
          }  
    }
    

提交回复
热议问题