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

import java.util.concurrent.TimeUnit;

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

    private long timeLeft() {
        return endTime - System.currentTimeMillis();
    }

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

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

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

    public boolean isTimeLeft() {
        return timeLeft() > 0;
    }
}