1 34 package net.myvietnam.mvncore.util; 35 36 import java.util.Timer ; 37 import java.util.TimerTask ; 38 import java.util.Date ; 39 import org.apache.commons.logging.Log; 40 import org.apache.commons.logging.LogFactory; 41 42 public final class TimerUtil { 43 44 private static Log log = LogFactory.getLog(TimerUtil.class); 46 47 private static TimerUtil instance = null; 49 50 private static boolean isCanceled = false; 52 53 private Timer timer = null; 55 56 private TimerUtil() { 58 log.debug("TimerUtil is instantiated."); 59 timer = new Timer (); 60 } 61 62 private void reloadTimer() { 63 log.info("Reload Timer in TimerUtil."); 64 if (!isCanceled) { 65 timer.cancel(); timer = new Timer (); 67 } 68 } 69 70 74 public static synchronized TimerUtil getInstance() { 75 if (instance == null) { 76 instance = new TimerUtil(); 77 } 78 return instance; 79 } 80 81 public void cancel() { 82 isCanceled = true; 83 timer.cancel(); 84 } 85 86 public void schedule(TimerTask task, Date firstTime, long period) { 87 if (!isCanceled) { 88 try { 89 timer.schedule(task, firstTime, period); 90 } catch (IllegalStateException ex) { 91 log.error("Cannot schedule task!", ex); 92 reloadTimer(); 93 } 94 } 95 } 96 97 public void schedule(TimerTask task, Date time) { 98 if (!isCanceled) { 99 try { 100 timer.schedule(task, time); 101 } catch (IllegalStateException ex) { 102 log.error("Cannot schedule task!", ex); 103 reloadTimer(); 104 } 105 } 106 } 107 108 public void schedule(TimerTask task, long delay) { 109 if (!isCanceled) { 110 try { 111 timer.schedule(task, delay); 112 } catch (IllegalStateException ex) { 113 log.error("Cannot schedule task!", ex); 114 reloadTimer(); 115 } 116 } 117 } 118 119 public void schedule(TimerTask task, long delay, long period) { 120 if (!isCanceled) { 121 try { 122 timer.schedule(task, delay, period); 123 } catch (IllegalStateException ex) { 124 log.error("Cannot schedule task!", ex); 125 reloadTimer(); 126 } 127 } 128 } 129 130 public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) { 131 if (!isCanceled) { 132 try { 133 timer.schedule(task, firstTime, period); 134 } catch (IllegalStateException ex) { 135 log.error("Cannot schedule task!", ex); 136 reloadTimer(); 137 } 138 } 139 } 140 141 public void scheduleAtFixedRate(TimerTask task, long delay, long period) { 142 if (!isCanceled) { 143 try { 144 timer.schedule(task, delay, period); 145 } catch (IllegalStateException ex) { 146 log.error("Cannot schedule task!", ex); 147 reloadTimer(); 148 } 149 } 150 } 151 } 152 | Popular Tags |