Skip to content

Commit 0ccd40b

Browse files
authored
Fix unstable TimerTest (#5956)
Closes #5937 (cherry picked from commit 854dd26)
1 parent 31aff1a commit 0ccd40b

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

vertx-core/src/test/java/io/vertx/tests/timer/TimerTest.java

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import io.vertx.core.internal.VertxInternal;
1818
import io.vertx.test.core.Repeat;
1919
import io.vertx.test.core.VertxTestBase;
20+
import org.hamcrest.Matchers;
2021
import org.junit.Test;
2122

2223
import java.util.concurrent.CancellationException;
@@ -62,13 +63,13 @@ public void testPeriodicWithInitialDelay2() {
6263
*/
6364
@Test
6465
public void testTimings() {
65-
final long start = System.currentTimeMillis();
66+
final long start = System.nanoTime();
6667
final long delay = 2000;
6768
vertx.setTimer(delay, timerID -> {
68-
long dur = System.currentTimeMillis() - start;
69-
assertTrue(dur >= delay);
69+
long dur = System.nanoTime() - start;
70+
assertTrue(dur >= TimeUnit.MILLISECONDS.toNanos(delay));
7071
long maxDelay = delay * 2;
71-
assertTrue("Timer accuracy: " + dur + " vs " + maxDelay, dur < maxDelay); // 100% margin of error (needed for CI)
72+
assertTrue("Timer accuracy: " + dur + " vs " + TimeUnit.MILLISECONDS.toNanos(maxDelay), dur < TimeUnit.MILLISECONDS.toNanos(maxDelay)); // 100% margin of error (needed for CI)
7273
vertx.cancelTimer(timerID);
7374
testComplete();
7475
});
@@ -119,11 +120,11 @@ static class PeriodicArg {
119120
private void periodic(PeriodicArg delay, BiFunction<PeriodicArg, Handler<Long>, Long> abc) {
120121
final int numFires = 10;
121122
final AtomicLong id = new AtomicLong(-1);
122-
long now = System.currentTimeMillis();
123+
long now = System.nanoTime();
123124
id.set(abc.apply(delay, new Handler<Long>() {
124125
int count;
125126
public void handle(Long timerID) {
126-
assertTrue( System.currentTimeMillis() - now >= delay.initialDelay + count * delay.delay);
127+
assertThat(System.nanoTime() - now, Matchers.greaterThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(delay.initialDelay + count * delay.delay)));
127128
assertEquals(id.get(), timerID.longValue());
128129
count++;
129130
if (count == numFires) {
@@ -363,10 +364,10 @@ public void start() throws Exception {
363364

364365
@Test
365366
public void testTimerFire() {
366-
long now = System.currentTimeMillis();
367+
long now = System.nanoTime();
367368
Timer timer = vertx.timer(1, TimeUnit.SECONDS);
368369
timer.onComplete(onSuccess(v -> {
369-
assertTrue(System.currentTimeMillis() - now >= 800);
370+
assertTrue(System.nanoTime() - now >= TimeUnit.SECONDS.toNanos(1));
370371
testComplete();
371372
}));
372373
await();

0 commit comments

Comments
 (0)