Using Thread.Sleep() in a Windows Service

后端 未结 5 1001
萌比男神i
萌比男神i 2021-02-04 07:46

I\'m writing a windows service that needs to sleep for long periods of time (15 hrs is the longest it will sleep, 30 mins is the shortest). I\'m currently using Thread.

5条回答
  •  执笔经年
    2021-02-04 07:55

    You should not pre-calculate such large amounts of time and sleep for hours. Sleep for a minute at best, then wake up and re-calculate the time, sleep again for no more that a minute. I assume the calculation is very cheap or it can be made very cheap with caching. The problem my advise is trying to mitigate is that computer clocks are surprisingly 'jumpy', mostly due to time drift corrected by network time service, also because of daylights savings and not least because user adjusting the clock. So is better to constantly recompute the time for such long intervals, even if it means waking up every minute or so. And don't be surprised (ie. don't assert) if you wake up in the 'past', clocks can adjust back in time.

提交回复
热议问题