| 1 | |
package expectj; |
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
class Timer implements Runnable { |
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | 6138 | private long timeOut = 0; |
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | 6138 | private TimerEventListener listener = null; |
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | 6138 | private Thread thread = null; |
| 23 | |
|
| 24 | |
|
| 25 | |
|
| 26 | |
|
| 27 | |
public static final int NOT_STARTED = 0; |
| 28 | |
|
| 29 | |
|
| 30 | |
|
| 31 | |
|
| 32 | |
public static final int STARTED = 1; |
| 33 | |
|
| 34 | |
|
| 35 | |
|
| 36 | |
|
| 37 | |
public static final int TIMEDOUT = 2; |
| 38 | |
|
| 39 | |
|
| 40 | |
|
| 41 | |
|
| 42 | |
public static final int INTERRUPTED = 3; |
| 43 | |
|
| 44 | |
|
| 45 | |
|
| 46 | |
|
| 47 | 6138 | private int currentStatus = NOT_STARTED; |
| 48 | |
|
| 49 | |
|
| 50 | |
|
| 51 | |
|
| 52 | 6138 | private boolean done = false; |
| 53 | |
|
| 54 | |
|
| 55 | |
|
| 56 | |
|
| 57 | |
|
| 58 | |
|
| 59 | |
|
| 60 | |
|
| 61 | |
|
| 62 | 6138 | public Timer(long timeOut, TimerEventListener listener) { |
| 63 | |
|
| 64 | 6138 | if (timeOut < 1) { |
| 65 | 0 | throw new IllegalArgumentException("Time-Out value cannot be < 1"); |
| 66 | |
} |
| 67 | 6138 | if (listener == null ) { |
| 68 | 0 | throw new IllegalArgumentException("Listener cannot be null"); |
| 69 | |
} |
| 70 | 6138 | this.timeOut = timeOut * 1000; |
| 71 | 6138 | this.listener = listener; |
| 72 | |
|
| 73 | 6138 | } |
| 74 | |
|
| 75 | |
|
| 76 | |
|
| 77 | |
|
| 78 | |
public void startTimer() { |
| 79 | 6123 | thread = new Thread(this, "ExpectJ Timer Thread, " + timeOut + "ms"); |
| 80 | 6123 | currentStatus = STARTED; |
| 81 | 6123 | thread.start(); |
| 82 | 6123 | } |
| 83 | |
|
| 84 | |
|
| 85 | |
|
| 86 | |
|
| 87 | |
|
| 88 | |
|
| 89 | |
|
| 90 | |
public int getStatus() { |
| 91 | 4080 | return currentStatus; |
| 92 | |
} |
| 93 | |
|
| 94 | |
|
| 95 | |
|
| 96 | |
|
| 97 | |
|
| 98 | |
public void close() { |
| 99 | 4080 | synchronized (this) { |
| 100 | 4080 | done = true; |
| 101 | 4080 | this.notify(); |
| 102 | 4080 | } |
| 103 | 4080 | } |
| 104 | |
|
| 105 | |
|
| 106 | |
|
| 107 | |
|
| 108 | |
public void run() { |
| 109 | |
try { |
| 110 | |
|
| 111 | 6123 | synchronized (this) { |
| 112 | 6123 | this.wait(timeOut); |
| 113 | 5888 | if (done) { |
| 114 | |
|
| 115 | 4079 | return; |
| 116 | |
} |
| 117 | |
|
| 118 | |
|
| 119 | 1809 | currentStatus = TIMEDOUT; |
| 120 | 1809 | listener.timerTimedOut(); |
| 121 | 1809 | } |
| 122 | 0 | } catch (InterruptedException iexp) { |
| 123 | 0 | currentStatus = INTERRUPTED; |
| 124 | 0 | listener.timerInterrupted(iexp); |
| 125 | 1809 | } |
| 126 | 1809 | } |
| 127 | |
} |