1 21 package com.scalagent.kjoram.util; 22 23 import java.util.Vector ; 24 25 30 public class Timer 31 { 32 33 private boolean cancelled = false; 34 35 TimerDaemon daemon; 36 37 Vector tasks; 38 39 40 public Timer() 41 { 42 tasks = new Vector (); 43 daemon = new TimerDaemon(this); 44 } 45 46 55 public synchronized void schedule(TimerTask task, long delay) 56 throws Exception 57 { 58 if (cancelled) 59 throw new IllegalStateException ("Timer has been cancelled."); 60 if (tasks.contains(task)) 61 throw new IllegalStateException ("Task is already scheduled."); 62 if (task.cancelled) 63 throw new IllegalStateException ("Task has been cancelled."); 64 65 if (delay < 0) 66 throw new IllegalArgumentException ("Invalid negative delay: " + delay); 67 68 long wakeupTime = System.currentTimeMillis() + delay; 69 insertTask(task, wakeupTime); 70 71 if (wakeupTime < daemon.nextWakeup) 72 daemon.interrupt(); 73 74 if (! daemon.started) 75 daemon.start(); 76 } 77 78 79 public synchronized void cancel() 80 { 81 cancelled = true; 82 83 if (! daemon.started) 84 return; 85 86 tasks.removeAllElements(); 87 88 daemon.interrupt(); 89 } 90 91 92 private void insertTask(TimerTask task, long wakeupTime) 93 { 94 task.timer = this; 95 task.wakeupTime = wakeupTime; 96 97 int i = 0; 98 TimerTask currentTask; 99 while (i < tasks.size()) { 100 currentTask = (TimerTask) tasks.elementAt(i); 101 102 if (currentTask.wakeupTime > wakeupTime) { 103 tasks.insertElementAt(task, i); 104 break; 105 } 106 else 107 i++; 108 } 109 if (i == tasks.size()) 110 tasks.addElement(task); 111 } 112 } 113 114 115 116 class TimerDaemon extends Daemon 117 { 118 119 private Timer timer; 120 121 private boolean waiting = false; 122 123 long nextWakeup = -1; 124 125 boolean started = false; 126 127 128 129 TimerDaemon(Timer timer) 130 { 131 super("timer"); 132 setDaemon(true); 133 this.timer = timer; 134 } 135 136 137 public void start() 138 { 139 super.start(); 140 started = true; 141 } 142 143 144 public void run() 145 { 146 try { 147 TimerTask task = null; 148 while (running) { 149 canStop = true; 150 151 synchronized (timer) { 152 if (timer.tasks.isEmpty()) { 153 started = false; 154 break; 155 } 156 157 task = (TimerTask) timer.tasks.elementAt(0); 158 nextWakeup = task.wakeupTime; 159 } 160 161 try { 162 synchronized (this) { 163 waiting = true; 164 task.waiting = true; 165 try { 166 this.wait(nextWakeup - System.currentTimeMillis()); 167 } 168 catch (IllegalArgumentException illAE) {} 169 } 170 171 synchronized (timer) { 172 canStop = false; 173 waiting = false; 174 nextWakeup = -1; 175 task.run(); 176 timer.tasks.removeElement(task); 177 } 178 } 179 catch (InterruptedException iE0) {} 180 } 181 } 182 catch (Exception e) {} 183 finally { 184 finish(); 185 } 186 } 187 188 189 public synchronized void interrupt() 190 { 191 if (waiting) 192 stop(); 194 } 195 196 197 public void shutdown() 198 {} 199 200 201 public void close() 202 {} 203 } 204 | Popular Tags |