aboutsummaryrefslogtreecommitdiffstats
path: root/fileacquirer/src/main/java/com/yahoo/filedistribution/fileacquirer/Timer.java
blob: e8c08edb621a1073b946217c1b3c01fa946d5389 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.filedistribution.fileacquirer;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * Handles timeout of a task.
 * @author Tony Vaagenes
 */
class Timer {
    private final long endTime;

    private Duration timeLeft() {
        return Duration.ofNanos(endTime - System.nanoTime());
    }

    public Timer(long timeout, TimeUnit timeUnit) {
        endTime = System.nanoTime() + timeUnit.toNanos(timeout);
    }

    public long timeLeft(TimeUnit timeUnit) {
        long remaining = timeUnit.convert(timeLeft().toMillis(), TimeUnit.MILLISECONDS);

        if (remaining > 0)
            return remaining;
        else
            throw new TimeoutException("Timed out");
    }

    public boolean isTimeLeft() {
        return ! timeLeft().isNegative();
    }
}