1 package expectj;
2
3
4 /***
5 * This class acts like a timer and invokes the listener on time-out.
6 */
7 class Timer implements Runnable {
8 /***
9 * The time interval in milliseconds up to which the process
10 * should be allowed to run.
11 */
12 private long timeOut = 0;
13
14 /***
15 * The entity that wants to be notified on timeout.
16 */
17 private TimerEventListener listener = null;
18
19 /***
20 * The waiting thread.
21 */
22 private Thread thread = null;
23
24 /***
25 * Timer not started.
26 */
27 public static final int NOT_STARTED = 0;
28
29 /***
30 * Timer started and still running.
31 */
32 public static final int STARTED = 1;
33
34 /***
35 * Timer timed out.
36 */
37 public static final int TIMEDOUT = 2;
38
39 /***
40 * Timer interrupted.
41 */
42 public static final int INTERRUPTED = 3;
43
44 /***
45 * Stores the current status of Timer
46 */
47 private int currentStatus = NOT_STARTED;
48
49 /***
50 * Are we there yet?
51 */
52 private boolean done = false;
53
54 /***
55 * Constructor
56 *
57 * @param timeOut Time interval after which the listener will be
58 * invoked
59 * @param listener Object implementing the TimerEventListener
60 * interface
61 */
62 public Timer(long timeOut, TimerEventListener listener) {
63
64 if (timeOut < 1) {
65 throw new IllegalArgumentException("Time-Out value cannot be < 1");
66 }
67 if (listener == null ) {
68 throw new IllegalArgumentException("Listener cannot be null");
69 }
70 this.timeOut = timeOut * 1000;
71 this.listener = listener;
72
73 }
74
75 /***
76 * Starts the timer
77 */
78 public void startTimer() {
79 thread = new Thread(this, "ExpectJ Timer Thread, " + timeOut + "ms");
80 currentStatus = STARTED;
81 thread.start();
82 }
83
84 /***
85 * Return timer status. Can be one of {@link #NOT_STARTED}, {@link #STARTED},
86 * {@link #TIMEDOUT} or {@link #INTERRUPTED}.
87 *
88 * @return the status of the timer
89 */
90 public int getStatus() {
91 return currentStatus;
92 }
93
94 /***
95 * Close the timer prematurely. The event listener won't get any
96 * notifications.
97 */
98 public void close() {
99 synchronized (this) {
100 done = true;
101 this.notify();
102 }
103 }
104
105 /***
106 * This is the timer thread main.
107 */
108 public void run() {
109 try {
110
111 synchronized (this) {
112 this.wait(timeOut);
113 if (done) {
114
115 return;
116 }
117
118
119 currentStatus = TIMEDOUT;
120 listener.timerTimedOut();
121 }
122 } catch (InterruptedException iexp) {
123 currentStatus = INTERRUPTED;
124 listener.timerInterrupted(iexp);
125 }
126 }
127 }