Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleeping till NEXT Second

I am finding often the need to very often wait until the next second to do the next operation in a series. This slows down unit tests quite considerably. So here's my question:

Instead of doing Thread.sleep(1000) is there a quicker more efficient way to sleep until the second changes to the next second?

Say the time is 1:00:89

I sleep one second to 1:01:89

I would rather continuing executing when the time hits 1:01 or as close as possible.

Is this reasonably possible? ^_^

like image 465
bobber205 Avatar asked Dec 17 '22 22:12

bobber205


2 Answers

Well, you could do something like:

long millisWithinSecond = System.currentTimeMillis() % 1000;
Thread.sleep(1000 - millisWithinSecond);

It won't be exact, mind you - you may need to iterate, which is a bit messy.

However, it would be better not to have to sleep at all. Could you inject a "sleeping service" which would allow you to fake the sleeps out in tests? (I've rarely needed to do that, but I've often injected a fake clock to report different times.) What's the purpose of sleeping in the production code at all?

like image 99
Jon Skeet Avatar answered Dec 28 '22 10:12

Jon Skeet


When you say "the second", do you mean the second of the system clock? You can get the current time in milliseconds via System.currentTimeMillis(), then subtract that from 1000 and sleep by that amount, but keep in mind that Thread.sleep() is not perfectly accurate, so don't be surprised if you overshoot by a bit.

like image 30
EboMike Avatar answered Dec 28 '22 10:12

EboMike