Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread sleep/wait until a new day

I'm running a process in a loop which has a limit on the number of operations it does per day. When it reaches this limit I've currently got it checking the the time in a loop to see if it a new date.

Would the best option be to:

  • Keep checking the time every second for new date
  • Calculate the number of seconds until midnight and sleep that length of time
  • Something else?
like image 334
finoutlook Avatar asked Sep 16 '11 13:09

finoutlook


People also ask

How long should thread sleep?

If it is a UI worker thread, as long as they have some kind of progress indicator, anywhere up to half a second should be good enough. The UI should be responsive during the operation since its a background thread and you definitely have enough CPU time available to check every 500 ms.

Is it a good practice to use thread sleep?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

What is sleep () method?

sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .

What happens during thread sleep?

Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.


1 Answers

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.

like image 190
Dan Herbert Avatar answered Sep 19 '22 14:09

Dan Herbert