-
Notifications
You must be signed in to change notification settings - Fork 3
/
Timer.java
84 lines (68 loc) · 2.34 KB
/
Timer.java
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package timer;
import net.jcip.annotations.ThreadSafe;
import static com.google.common.base.Preconditions.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
/**
* Created by kennylbj on 16/8/27.
* Timer is designed to be thread-safe.
*
*/
@ThreadSafe
public class Timer {
private static final int SECONDS_TO_NANOSECONDS = 1000 * 1000 * 1000;
//in order to add task from other threads.
private final BlockingQueue<TimerEvent> timers;
private volatile boolean stop = false;
public Timer() {
timers = new PriorityBlockingQueue<>();
}
public void addTimerEventInSeconds(long expirationTime, Runnable task) {
addTimerEventInNanoSeconds(expirationTime * SECONDS_TO_NANOSECONDS, task);
}
public void addTimerEventInNanoSeconds(long expirationTime, Runnable task) {
checkArgument(expirationTime >= 0, "expiration time can't not less than 0");
checkNotNull(task);
long expirationNs = System.nanoTime() + expirationTime;
timers.add(new TimerEvent(expirationNs, task));
}
//FIXME wait and notify
public void loop() {
while (!stop) {
triggerExpiredTimers(System.nanoTime());
}
}
public void stop() {
stop = true;
}
//FIXME should we synchronize it? timers will only be add but never
//removed from other thread, so it's safe to do in this way.
private void triggerExpiredTimers(long currentTime) {
while (!timers.isEmpty()) {
long nextExpiredTime = timers.peek().getExpirationTime();
if (nextExpiredTime <= currentTime) {
timers.poll().getTask().run();
} else {
return;
}
}
}
private static class TimerEvent implements Comparable<TimerEvent> {
private final long expirationTime;
private final Runnable task;
TimerEvent(long expirationTime, Runnable task) {
this.expirationTime = expirationTime;
this.task = task;
}
@Override
public int compareTo(TimerEvent other) {
return Long.compare(expirationTime, other.expirationTime);
}
public long getExpirationTime() {
return expirationTime;
}
public Runnable getTask() {
return task;
}
}
}