1 19 20 package com.jtheory.jdring; 21 22 30 public class AlarmWaiter implements Runnable { 31 protected AlarmManager mgr; 32 protected Thread thread; 33 private long sleepUntil = -1; 34 private boolean debug = false; 35 private boolean shutdown = false; 36 37 private void debug(String s) { 38 if (debug) 39 System.out.println("[" + Thread.currentThread().getName() + "] AlarmWaiter: " + s); 40 } 41 42 48 public AlarmWaiter(AlarmManager mgr, boolean isDaemon, String waiterName) { 49 this.mgr = mgr; 50 51 thread = new Thread (this, waiterName); 53 thread.setPriority( 1 ); 54 thread.setDaemon(isDaemon); 55 thread.start(); 56 } 57 58 63 public synchronized void update(long _sleep_until) { 64 this.sleepUntil = _sleep_until; 65 debug("Update for " + _sleep_until); debug("calling notify() to update thread wait timeout"); 67 notify(); 68 } 69 70 75 public synchronized void restart(long _sleep_until) { 76 this.sleepUntil = _sleep_until; 77 notify(); 78 } 79 80 83 public synchronized void stop() { 84 shutdown = true; 85 notify(); 86 } 87 88 89 public synchronized void run() { 90 debug("running"); 91 while(!shutdown) { 92 try { 93 if (sleepUntil <= 0) { 95 wait(); 97 } else { 99 long timeout = sleepUntil - System.currentTimeMillis(); 101 if (timeout > 0) { 102 wait(timeout); 103 } 104 } 105 106 if (sleepUntil >= 0 && (sleepUntil - System.currentTimeMillis() < 1000)) { 109 sleepUntil = -1; 111 debug("notifying manager to ring next alarm"); 112 mgr.ringNextAlarm(); 113 } 114 115 } 116 catch(InterruptedException e) { 117 debug("interrupted"); 118 } 119 } 120 debug("stopping"); 121 } 122 123 } 124 125 126 | Popular Tags |