1 10 package org.mmbase.core.util; 11 12 import org.mmbase.module.core.MMBaseContext; 13 import org.mmbase.util.logging.*; 14 15 21 public class DaemonThread extends Thread implements DaemonTask { 22 23 26 public static final int DEFAULT_SLEEP_PERIOD = 60000; 27 28 private static final Logger log = Logging.getLoggerInstance(DaemonThread.class); 29 30 35 protected int sleepPeriod = DEFAULT_SLEEP_PERIOD; 36 37 private Runnable target = null; 38 private DaemonTask task = null; 39 private boolean running = false; 40 41 44 public DaemonThread() { 45 this((Runnable )null, (String )null); 46 } 47 48 52 public DaemonThread(String name) { 53 this((Runnable )null, name); 54 } 55 56 61 public DaemonThread(Runnable target, String name) { 62 super(MMBaseContext.getThreadGroup(), target, name); 63 this.target = target; 64 setDaemon(true); 65 } 66 67 71 public void setTask(DaemonTask task) { 72 this.task = task; 73 } 74 75 78 public DaemonTask getTask() { 79 return task; 80 } 81 82 public int getSleepPeriod() { 83 if (task != null) { 84 return task.getSleepPeriod(); 85 } else { 86 return sleepPeriod; 87 } 88 } 89 90 public void start() { 91 running = true; 92 log.service("Starting " + getName()); 93 super.start(); 94 } 95 96 public void interrupt() { 97 running = false; 98 super.interrupt(); 99 } 100 101 public boolean isRunning() { 102 return running; 103 } 104 105 public void executeTask() { 106 if (task != null) { 107 task.executeTask(); 108 } else { 109 throw new UnsupportedOperationException ("No execute task defined"); 110 } 111 } 112 113 116 public void run() { 117 if (target != null) { 118 target.run(); 119 } else { 120 while (isRunning()) { 121 try { 122 Thread.sleep(getSleepPeriod()); 123 executeTask(); 124 } catch (InterruptedException e){ 125 log.debug(Thread.currentThread().getName() +" was interrupted."); 126 } 127 } 128 } 129 } 130 131 } 132 133 | Popular Tags |