Thread sleep/wait until a new day Thread sleep/wait until a new day multithreading multithreading

Thread sleep/wait until a new day


Don't use Thread.Sleep for this type of thing. Use a Timer and calculate the duration you need to wait.

var now = DateTime.Now;var tomorrow = now.AddDays(1);var durationUntilMidnight = tomorrow.Date - now;var t = new Timer(o=>{/* Do work*/}, null, TimeSpan.Zero, durationUntilMidnight);

Replace the /* Do Work */ delegate with the callback that will resume your work at the specified interval.

Edit: As mentioned in the comments, there are many things that can go wrong if you assume the "elapsed time" an application will wait for is going to match real-world time. For this reason, if timing is important to you, it is better to use smaller polling intervals to find out if the clock has reached the time you want your work to happen at.

Even better would be to use Windows Task Scheduler to run your task at the desired time. This will be much more reliable than trying to implement it yourself in code.


Windows has a task scheduler that handles exactly this duty. Create the program to do that which it is supposed to do. Then set it up as a scheduled task.


Just calculate a period to wait and run an asynchronous timer in this way you can avoid extra CPU consuming whilst waiting:

var nextDateStartDateTime = DateTime.Now.AddDays(1).Subtract(DateTime.Now.TimeOfDay);double millisecondsToWait = (nextDateStartDateTime - DateTime.Now).TotalMilliseconds;System.Threading.Timer timer = new Timer(    (o) => { Debug.WriteLine("New day comming on"); },    null,    (uint)millisecondsToWait    0);