Sleep until the next second

I often find myself waiting very often for the next episode in the following sequence. This significantly slows down the testing process. So here is my question:

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

Say the time is 1:00:89

I sleep one second until 1:01:89

I would rather continue doing it when the time is 1:01 or as close as possible.

Is it possible? ^ _ ^

+4
source share
2 answers

Ok, you could do something like:

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

It will not be accurate, mind you - you may need to repeat that a bit messy.

However, it would be better not to sleep at all. Could you introduce a "sleeping service" that will allow you to fake a dream in tests? (I rarely needed to do this, but I often entered fake watches to tell different times.) What is the purpose of sleeping in production code in general?

+10
source

When you say β€œsecond,” do you mean the second of the system clocks? You can get the current time in milliseconds using System.currentTimeMillis() and then subtract from 1000 and sleep for that amount, but keep in mind that Thread.sleep () is not entirely accurate, so don't be surprised if you exceed the bit.

+1
source

All Articles