1 16 17 package org.springframework.scheduling.timer; 18 19 import java.util.Timer ; 20 21 import org.apache.commons.logging.Log; 22 import org.apache.commons.logging.LogFactory; 23 24 import org.springframework.beans.factory.DisposableBean; 25 import org.springframework.beans.factory.InitializingBean; 26 import org.springframework.scheduling.SchedulingTaskExecutor; 27 import org.springframework.util.Assert; 28 29 38 public class TimerTaskExecutor implements SchedulingTaskExecutor, InitializingBean, DisposableBean { 39 40 43 protected final Log logger = LogFactory.getLog(getClass()); 44 45 private Timer timer; 46 47 private int delay = 0; 48 49 private boolean usingAnInternalTimer = false; 50 51 52 58 public TimerTaskExecutor() { 59 } 60 61 66 public TimerTaskExecutor(Timer timer) { 67 Assert.notNull(timer, "Timer must not be null"); 68 this.timer = timer; 69 } 70 71 79 public void setTimer(Timer timer) { 80 this.timer = timer; 81 } 82 83 88 public void setDelay(int delay) { 89 this.delay = delay; 90 } 91 92 93 public void afterPropertiesSet() { 94 if (this.timer == null) { 95 logger.info("Initializing Timer"); 96 this.timer = createTimer(); 97 this.usingAnInternalTimer = true; 98 } 99 } 100 101 111 protected Timer createTimer() { 112 return new Timer (true); 113 } 114 115 116 124 public void execute(Runnable task) { 125 Assert.notNull(this.timer, "timer is required"); 126 this.timer.schedule(new DelegatingTimerTask(task), this.delay); 127 } 128 129 132 public boolean prefersShortLivedTasks() { 133 return true; 134 } 135 136 137 141 public void destroy() { 142 if (this.usingAnInternalTimer) { 143 logger.info("Cancelling Timer"); 144 this.timer.cancel(); 145 } 146 } 147 148 } 149 | Popular Tags |