views:

89

answers:

2

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? ^_^

+8  A: 

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?

Jon Skeet
+1 for noting that you shouldn't be sleeping in unit tests/production code
I82Much
You won't have to iterate because the sleep method guarantees the Thread sleeps for at least as long as the time specified (though it may sleep longer)... +1 anyway for a good answer.
Tim Bender
A: 

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.

EboMike