1 20 21 22 23 package org.snmp4j.util; 24 25 import java.util.LinkedList ; 26 import org.snmp4j.log.LogFactory; 27 import org.snmp4j.log.LogAdapter; 28 29 37 public class TaskScheduler implements Runnable { 38 39 private LogAdapter logger = LogFactory.getLogger(TaskScheduler.class); 40 41 private static final long DEFAULT_SCHEDULER_TIMEOUT = 5; 42 43 private LinkedList tasks = new LinkedList (); 44 private ThreadPool threadPool; 45 private boolean stop; 46 protected long schedulerTimeout = DEFAULT_SCHEDULER_TIMEOUT; 47 48 55 public TaskScheduler(ThreadPool threadPool) { 56 this.threadPool = threadPool; 57 } 58 59 64 public synchronized void addTask(SchedulerTask task) { 65 tasks.addLast(task); 66 notify(); 67 } 68 69 76 public synchronized boolean removeTask(SchedulerTask task) { 77 return tasks.remove(task); 78 } 79 80 83 public synchronized void clear() { 84 tasks.clear(); 85 } 86 87 91 public void run() { 92 while (!stop) { 93 boolean readyToRun = false; 94 synchronized (this) { 95 for (int i=0; i<tasks.size(); i++) { 96 SchedulerTask task = (SchedulerTask) tasks.get(i); 97 if (task.isDone()) { 98 if (logger.isDebugEnabled()) { 99 logger.debug("Task '" + task + "' is done"); 100 } 101 tasks.removeFirst(); 102 continue; 103 } 104 else if (task.isReadyToRun()) { 105 readyToRun = true; 106 while (!threadPool.tryToExecute(task)) { 107 try { 108 synchronized (threadPool) { 109 threadPool.wait(schedulerTimeout); 110 } 111 } 112 catch (InterruptedException ex) { 113 logger.warn("Scheduler interrupted, aborting..."); 114 stop = true; 115 break; 116 } 117 } 118 tasks.addLast(tasks.removeFirst()); 119 i--; 120 } 121 } 122 } 123 if (!readyToRun) { 124 try { 125 if (threadPool.isIdle()) { 126 synchronized (this) { 127 wait(schedulerTimeout); 128 } 129 } 130 else { 131 synchronized (threadPool) { 132 threadPool.wait(schedulerTimeout); 133 } 134 } 135 } 136 catch (InterruptedException ex1) { 137 logger.warn("Scheduler interrupted, aborting..."); 138 stop = true; 139 } 140 } 141 } 142 logger.info("Scheduler stopped."); 143 } 144 145 150 public void setStop(boolean stop) { 151 this.stop = stop; 152 } 153 154 159 public boolean isStop() { 160 return stop; 161 } 162 } 163 | Popular Tags |