KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > scheduling > timer > TimerFactoryBean


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.scheduling.timer;
18
19 import java.util.Timer JavaDoc;
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 /**
33  * FactoryBean that sets up a {@link java.util.Timer} and exposes it for bean references.
34  *
35  * <p>Allows for registration of {@link ScheduledTimerTask ScheduledTimerTasks},
36  * automatically starting the {@link Timer} on initialization and cancelling it
37  * on destruction of the context. In scenarios that just require static registration
38  * of tasks at startup, there is no need to access the {@link Timer} instance itself
39  * in application code at all.
40  *
41  * <p>Note that the {@link Timer} mechanism uses a {@link java.util.TimerTask}
42  * instance that is shared between repeated executions, in contrast to Quartz
43  * which creates a new Job instance for each execution.
44  *
45  * @author Juergen Hoeller
46  * @since 19.02.2004
47  * @see ScheduledTimerTask
48  * @see java.util.Timer
49  * @see java.util.TimerTask
50  */

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 JavaDoc beanName;
60
61     private Timer JavaDoc timer;
62
63
64     /**
65      * Register a list of ScheduledTimerTask objects with the Timer that
66      * this FactoryBean creates. Depending on each SchedulerTimerTask's
67      * settings, it will be registered via one of Timer's schedule methods.
68      * @see java.util.Timer#schedule(java.util.TimerTask, long)
69      * @see java.util.Timer#schedule(java.util.TimerTask, long, long)
70      * @see java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long, long)
71      */

72     public void setScheduledTimerTasks(ScheduledTimerTask[] scheduledTimerTasks) {
73         this.scheduledTimerTasks = scheduledTimerTasks;
74     }
75
76     /**
77      * Set whether the timer should use a daemon thread,
78      * just executing as long as the application itself is running.
79      * <p>Default is "false": The timer will automatically get cancelled on
80      * destruction of this FactoryBean. Hence, if the application shuts down,
81      * tasks will by default finish their execution. Specify "true" for eager
82      * shutdown of threads that execute tasks.
83      * @see java.util.Timer#Timer(boolean)
84      */

85     public void setDaemon(boolean daemon) {
86         this.daemon = daemon;
87     }
88
89     public void setBeanName(String JavaDoc 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         // Register specified ScheduledTimerTasks, if necessary.
99
if (!ObjectUtils.isEmpty(this.scheduledTimerTasks)) {
100             registerTasks(this.scheduledTimerTasks, this.timer);
101         }
102     }
103
104     /**
105      * Create a new Timer instance. Called by <code>afterPropertiesSet</code>.
106      * Can be overridden in subclasses to provide custom Timer subclasses.
107      * <p>Uses the specified name as Timer thread name on JDK 1.5,
108      * simply falling back to a default Timer thread on JDK 1.3 and 1.4.
109      * @param name the desired name of the Timer's associated thread
110      * (applied on JDK 1.5 and higher; ignored on JDK 1.3 and 1.4)
111      * @param daemon whether to create a Timer that runs as daemon thread
112      * @return a new Timer instance
113      * @see #afterPropertiesSet()
114      * @see java.util.Timer#Timer(boolean)
115      */

116     protected Timer JavaDoc createTimer(String JavaDoc name, boolean daemon) {
117         Timer JavaDoc timer = createTimer(daemon);
118         if (timer != null) {
119             return timer;
120         }
121         if (StringUtils.hasText(name) && JdkVersion.isAtLeastJava15()) {
122             return new Timer JavaDoc(name, daemon);
123         }
124         else {
125             return new Timer JavaDoc(daemon);
126         }
127     }
128
129     /**
130      * Create a new Timer instance. Called by <code>afterPropertiesSet</code>.
131      * Can be overridden in subclasses to provide custom Timer subclasses.
132      * @deprecated as of Spring 2.0.1, in favor of {@link #createTimer(String, boolean)}
133      */

134     protected Timer JavaDoc createTimer(boolean daemon) {
135         return null;
136     }
137
138     /**
139      * Register the specified {@link ScheduledTimerTask ScheduledTimerTasks}
140      * on the given {@link Timer}.
141      * @param tasks the specified ScheduledTimerTasks (never empty)
142      * @param timer the Timer to register the tasks on.
143      */

144     protected void registerTasks(ScheduledTimerTask[] tasks, Timer JavaDoc 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 JavaDoc getObject() {
163         return this.timer;
164     }
165
166     public Class JavaDoc getObjectType() {
167         return Timer JavaDoc.class;
168     }
169
170     public boolean isSingleton() {
171         return true;
172     }
173
174
175     /**
176      * Cancel the Timer on bean factory shutdown, stopping all scheduled tasks.
177      * @see java.util.Timer#cancel()
178      */

179     public void destroy() {
180         logger.info("Cancelling Timer");
181         this.timer.cancel();
182     }
183
184 }
185
Popular Tags