-
Notifications
You must be signed in to change notification settings - Fork 0
/
FakePeriodicRunner.java
79 lines (70 loc) · 2.45 KB
/
FakePeriodicRunner.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
package com.pervasivecode.utils.time.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.util.Objects;
import com.pervasivecode.utils.time.PeriodicRunner;
/**
* This is a fake implementation of {@link PeriodicRunner}, intended for use by test code.
*/
public final class FakePeriodicRunner implements PeriodicRunner {
private Runnable task = null;
public boolean started = false;
@Override
public void setPeriodicTask(Runnable task) {
checkState(!started,
"A task is already scheduled in this runner. Call stop() before setting a different "
+ "scheduled task, or create a new SimplePeriodicRunner instance to handle an "
+ "additional scheduled task.");
this.task = checkNotNull(task);
}
/**
* Set an internal flag saying that this runner is in the started state.
*
* @throws IllegalStateException if no task has been provided.
*/
@Override
public void start() {
checkState(task != null, "No periodic task has been set.");
checkState(!this.started, "The task has already been started.");
this.started = true;
}
/**
* Set an internal flag saying that this runner is <i>not</i> in the started state.
*
* @throws IllegalStateException if the task is already not in the started state.
*/
@Override
public void stop() {
checkState(started, "The periodic task is not running.");
this.started = false;
}
/**
* Simulate the periodic timer firing and running the {@link Runnable} task. This will invoke the
* specified task once.
* <p>
* This will also verify that this runner is in the started state: that is, that the
* {@link #start()} method has been called more recently than the last call to {@link #stop()}, if
* any.
*
* @throws IllegalStateException if this runner is not in the started state.
*/
public void runOnce() {
checkState(started, "The periodic task has not been started yet, or has been stopped.");
this.task.run();
}
@Override
public int hashCode() {
return Objects.hash(task, started);
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof FakePeriodicRunner)) {
return false;
}
FakePeriodicRunner otherRunner = (FakePeriodicRunner) other;
return otherRunner.started == started && Objects.equals(otherRunner.task, task);
}
}