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.BeanNameAware; 25 import org.springframework.beans.factory.DisposableBean; 26 import org.springframework.beans.factory.FactoryBean; 27 import org.springframework.beans.factory.InitializingBean; 28 import org.springframework.core.JdkVersion; 29 import org.springframework.util.ObjectUtils; 30 import org.springframework.util.StringUtils; 31 32 51 public class TimerFactoryBean implements FactoryBean, BeanNameAware, InitializingBean, DisposableBean { 52 53 protected final Log logger = LogFactory.getLog(getClass()); 54 55 private ScheduledTimerTask[] scheduledTimerTasks; 56 57 private boolean daemon = false; 58 59 private String beanName; 60 61 private Timer timer; 62 63 64 72 public void setScheduledTimerTasks(ScheduledTimerTask[] scheduledTimerTasks) { 73 this.scheduledTimerTasks = scheduledTimerTasks; 74 } 75 76 85 public void setDaemon(boolean daemon) { 86 this.daemon = daemon; 87 } 88 89 public void setBeanName(String beanName) { 90 this.beanName = beanName; 91 } 92 93 94 public void afterPropertiesSet() { 95 logger.info("Initializing Timer"); 96 this.timer = createTimer(this.beanName, this.daemon); 97 98 if (!ObjectUtils.isEmpty(this.scheduledTimerTasks)) { 100 registerTasks(this.scheduledTimerTasks, this.timer); 101 } 102 } 103 104 116 protected Timer createTimer(String name, boolean daemon) { 117 Timer timer = createTimer(daemon); 118 if (timer != null) { 119 return timer; 120 } 121 if (StringUtils.hasText(name) && JdkVersion.isAtLeastJava15()) { 122 return new Timer (name, daemon); 123 } 124 else { 125 return new Timer (daemon); 126 } 127 } 128 129 134 protected Timer createTimer(boolean daemon) { 135 return null; 136 } 137 138 144 protected void registerTasks(ScheduledTimerTask[] tasks, Timer timer) { 145 for (int i = 0; i < tasks.length; i++) { 146 ScheduledTimerTask task = tasks[i]; 147 if (task.isOneTimeTask()) { 148 timer.schedule(task.getTimerTask(), task.getDelay()); 149 } 150 else { 151 if (task.isFixedRate()) { 152 timer.scheduleAtFixedRate(task.getTimerTask(), task.getDelay(), task.getPeriod()); 153 } 154 else { 155 timer.schedule(task.getTimerTask(), task.getDelay(), task.getPeriod()); 156 } 157 } 158 } 159 } 160 161 162 public Object getObject() { 163 return this.timer; 164 } 165 166 public Class getObjectType() { 167 return Timer .class; 168 } 169 170 public boolean isSingleton() { 171 return true; 172 } 173 174 175 179 public void destroy() { 180 logger.info("Cancelling Timer"); 181 this.timer.cancel(); 182 } 183 184 } 185 | Popular Tags |