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? ^_^
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With