@Test public void sleepUntilRegular() throws InterruptedException { long start = System.currentTimeMillis(); for (int i = 1; i <= 100; i++) { ThreadUtil.sleepUntilMs(start + i); } long elapsed = System.currentTimeMillis() - start; assertTrue(elapsed >= 100); // this is probably also flaky as hell due to different scheduling behaviour of different // platforms. lets see how well it does. assertTrue(elapsed <= 125); }
@Test public void sleepUntilMsIntoThePast() throws InterruptedException { // 1000 times no sleep at all long tStart = System.nanoTime(); for (int i = 0; i < 1000; i++) { long tms = System.currentTimeMillis(); ThreadUtil.sleepUntilMs(tms - 10); // noop } long elapsed = (System.nanoTime() - tStart); // this should finish within a few hundred microseconds // but that would make the test very flaky due to os-specific scheduling assertTrue(elapsed < 25_000_1000); // 25ms }