-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathDebouncingTimer.java
More file actions
55 lines (41 loc) · 1.28 KB
/
Copy pathDebouncingTimer.java
File metadata and controls
55 lines (41 loc) · 1.28 KB
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
package de.peeeq.wurstio.languageserver;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class DebouncingTimer {
final private Runnable action;
final private ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
private boolean isReady = false;
private ScheduledFuture<?> fut;
public DebouncingTimer(Runnable action) {
this.action = action;
}
/** checks whether the timer is ready */
public synchronized boolean isReady() {
return isReady;
}
public synchronized void stop() {
if (fut != null) {
fut.cancel(true);
fut = null;
}
isReady = false;
}
public synchronized void start(Duration d) {
stop();
fut = es.schedule(() -> {
synchronized (DebouncingTimer.this) {
isReady = true;
}
action.run();
}, d.toMillis(), TimeUnit.MILLISECONDS);
}
/** marks timer as ready immediately and triggers action */
public synchronized void triggerNow() {
stop();
isReady = true;
action.run();
}
}