Instead of setting a time to start every second every 60 minutes, you can calculate the remaining time and set the timer to half (or some other fraction) of this. Thus, you do not check the time so much, but also maintain a certain degree of accuracy, since the timer interval reduces the time it takes to approach the target time.
For example, if you want to do something in 60 minutes, the timers will be aproximatly:
30:00:00, 15:00:00, 07:30:00, 03:45:00, ..., 00:00:01, RUN!
I use the following code to automatically restart the service once a day. I use the thread because I found the timers unreliable for a long time, while it is more expensive in this example, it is the only thing that is created for this purpose, so it does not matter.
(converted from VB.NET)
autoRestartThread = new System.Threading.Thread(autoRestartThreadRun); autoRestartThread.Start();
...
private void autoRestartThreadRun() { try { DateTime nextRestart = DateAndTime.Today.Add(CurrentSettings.AutoRestartTime); if (nextRestart < DateAndTime.Now) { nextRestart = nextRestart.AddDays(1); } while (true) { if (nextRestart < DateAndTime.Now) { LogInfo("Auto Restarting Service"); Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = string.Format("/C net stop {0} && net start {0}", "\"My Service Name\""); p.StartInfo.LoadUserProfile = false; p.StartInfo.UseShellExecute = false; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.StartInfo.CreateNoWindow = true; p.Start(); } else { dynamic sleepMs = Convert.ToInt32(Math.Max(1000, nextRestart.Subtract(DateAndTime.Now).TotalMilliseconds / 2)); System.Threading.Thread.Sleep(sleepMs); } } } catch (ThreadAbortException taex) { } catch (Exception ex) { LogError(ex); } }
Note. I set the minimum interval to 1000 ms, it may not be studied, reduced or deleted depending on the required accuracy.
Remember to also stop the thread / timer when closing the application.
apc Dec 18 '15 at 11:11 2015-12-18 11:11
source share