1 16 package com.google.gwt.user.client; 17 18 import com.google.gwt.core.client.GWT; 19 import com.google.gwt.core.client.GWT.UncaughtExceptionHandler; 20 21 import java.util.ArrayList ; 22 23 36 public abstract class Timer { 37 38 private static ArrayList timers = new ArrayList (); 39 40 static { 41 hookWindowClosing(); 42 } 43 44 private static native void clearInterval(int id) ; 47 48 private static native void clearTimeout(int id) ; 51 52 private static native int createInterval(Timer timer, int period) ; 57 58 private static native int createTimeout(Timer timer, int delay) ; 63 64 private static void hookWindowClosing() { 65 Window.addWindowCloseListener(new WindowCloseListener() { 67 public void onWindowClosed() { 68 while (timers.size() > 0) { 72 ((Timer) timers.get(0)).cancel(); 73 } 74 } 75 76 public String onWindowClosing() { 77 return null; 78 } 79 }); 80 } 81 82 private boolean isRepeating; 83 84 private int timerId; 85 86 89 public void cancel() { 90 if (isRepeating) { 91 clearInterval(timerId); 92 } else { 93 clearTimeout(timerId); 94 } 95 timers.remove(this); 96 } 97 98 102 public abstract void run(); 103 104 110 public void schedule(int delayMillis) { 111 if (delayMillis <= 0) { 112 throw new IllegalArgumentException ("must be positive"); 113 } 114 cancel(); 115 isRepeating = false; 116 timerId = createTimeout(this, delayMillis); 117 timers.add(this); 118 } 119 120 126 public void scheduleRepeating(int periodMillis) { 127 if (periodMillis <= 0) { 128 throw new IllegalArgumentException ("must be positive"); 129 } 130 cancel(); 131 isRepeating = true; 132 timerId = createInterval(this, periodMillis); 133 timers.add(this); 134 } 135 136 139 final void fire() { 140 UncaughtExceptionHandler handler = GWT.getUncaughtExceptionHandler(); 141 if (handler != null) { 142 fireAndCatch(handler); 143 } else { 144 fireImpl(); 145 } 146 } 147 148 private void fireAndCatch(UncaughtExceptionHandler handler) { 149 try { 150 fireImpl(); 151 } catch (Throwable e) { 152 handler.onUncaughtException(e); 153 } 154 } 155 156 private void fireImpl() { 157 if (!isRepeating) { 160 timers.remove(this); 161 } 162 163 run(); 165 } 166 } 167 | Popular Tags |