aboutsummaryrefslogtreecommitdiffstats
path: root/jdisc_core/src/main/java/com/yahoo/jdisc/test/TestTimer.java
blob: 3f1218bf6888469d5790b7c5065ce24060e2d4f8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.test;

import com.yahoo.jdisc.Timer;

import java.time.Duration;
import java.time.Instant;
import java.util.Objects;

/**
 * A {@link Timer} to be used in tests when the advancement of time needs to be controlled.
 *
 * @author hakonhall
 */
public class TestTimer implements Timer {
    private Instant instant;

    public TestTimer() {
        this(Instant.EPOCH);
    }

    public TestTimer(Instant instant) {
        this.instant = Objects.requireNonNull(instant);
    }

    public void setMillis(long millisSinceEpoch) {
        instant = Instant.ofEpochMilli(millisSinceEpoch);
    }

    public void advanceMillis(long millis) { advance(Duration.ofMillis(millis)); }
    public void advanceSeconds(long seconds) { advance(Duration.ofSeconds(seconds)); }
    public void advanceMinutes(long minutes) { advance(Duration.ofMinutes(minutes)); }
    public void advance(Duration duration) {
        instant = instant.plus(duration);
    }

    @Override
    public Instant currentTime() {
        return instant;
    }

    @Override
    public long currentTimeMillis() {
        return instant.toEpochMilli();
    }
}