Windows Service to run a function at specified time

后端 未结 7 1879
一生所求
一生所求 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:18

    Good answer (I used your code), but one problem with this line:

    _timer.Interval = _scheduleTime.Subtract(DateTime.Now).TotalSeconds * 1000;
    

    If DateTime.now is later than scheduleTime, you will go negative and this will generate an exception when assigning to timer.Interval.

    I used:

    if (DateTime.now > scheduleTime)
        scheduleTime = scheduleTime.AddHours(24);
    

    Then do the subtraction.

提交回复
热议问题