1 22 package org.jboss.util; 23 24 34 public class TimerQueue 35 extends WorkerQueue 36 { 37 39 42 private Heap m_heap; 43 44 46 50 public TimerQueue() 51 { 52 this("TimerTask Thread"); 53 } 54 57 public TimerQueue(String threadName) 58 { 59 super(threadName); 60 m_heap = new Heap(); 61 } 62 63 67 public void schedule(TimerTask t) 68 { 69 schedule(t, 0); 70 } 71 75 public void schedule(TimerTask t, long delay) 76 { 77 if (t == null) throw new IllegalArgumentException ("Can't schedule a null TimerTask"); 78 if (delay < 0) delay = 0; 79 t.setNextExecutionTime(System.currentTimeMillis() + delay); 80 putJob(t); 81 } 82 83 85 protected void putJobImpl(Executable task) 87 { 88 m_heap.insert(task); 89 ((TimerTask)task).setState(TimerTask.SCHEDULED); 90 notifyAll(); 91 } 92 protected Executable getJobImpl() throws InterruptedException 93 { 94 while (m_heap.peek() == null) 95 { 96 wait(); 97 } 98 TimerTask task = (TimerTask)m_heap.extract(); 99 switch (task.getState()) 100 { 101 case TimerTask.CANCELLED: 102 case TimerTask.EXECUTED: 103 task = null; 105 return getJobImpl(); 106 case TimerTask.NEW: 107 case TimerTask.SCHEDULED: 108 return task; 109 default: 110 throw new IllegalStateException ("TimerTask has an illegal state"); 111 } 112 } 113 protected Runnable createQueueLoop() 114 { 115 return new TimerTaskLoop(); 116 } 117 protected void clear() 118 { 119 super.clear(); 120 synchronized (this) 121 { 122 m_heap.clear(); 123 } 124 } 125 126 128 130 132 137 protected class TimerTaskLoop implements Runnable 138 { 139 public void run() 140 { 141 try 142 { 143 while (true) 144 { 145 try 146 { 147 TimerTask task = (TimerTask)getJob(); 149 long now = System.currentTimeMillis(); 150 long executionTime = task.getNextExecutionTime(); 151 long timeToWait = executionTime - now; 152 boolean runTask = timeToWait <= 0; 153 if (!runTask) 154 { 155 putJob(task); 159 Object mutex = TimerQueue.this; 160 synchronized (mutex) 161 { 162 mutex.wait(timeToWait); 164 } 165 } 166 else 167 { 168 if (task.isPeriodic()) 169 { 170 task.setNextExecutionTime(executionTime + task.getPeriod()); 172 putJob(task); 173 } 174 else 175 { 176 task.setState(TimerTask.EXECUTED); 179 } 180 task.execute(); 182 } 183 } 184 catch (InterruptedException x) 185 { 186 break; 188 } 189 catch (Exception e) 190 { 191 ThrowableHandler.add(ThrowableHandler.Type.ERROR, e); 192 } 193 } 194 } 195 finally {clear();} 196 } 197 } 198 } 199 | Popular Tags |