t just require static registration of tasks at startup,
* there is no need to access the Timer instance itself in application code.
*
*
Note that Timer uses a TimerTask instance that is shared between
* repeated executions,in contrast to Quartz which instantiates a new
* Job for each execution.
*
* @author Juergen Hoeller
* @since 19.02.2004
* @see ScheduledTimerTask
* @see java.util.Timer
* @see java.util.TimerTask
*/
public class TimerFactoryBean implements FactoryBean,InitializingBean,DisposableBean {
protected final Log logger = LogFactory.getLog(getClass());
private ScheduledTimerTask[] scheduledTimerTasks;
private boolean daemon = false ;
private Timer timer;
/**
* Register a list of ScheduledTimerTask objects with the Timer that
* this FactoryBean creates. Depending on each SchedulerTimerTask''s
* settings,it will be registered via one of Timer''s schedule methods.
* @see java.util.Timer#schedule(java.util.TimerTask,long)
* @see java.util.Timer#schedule(java.util.TimerTask,long,long)
* @see java.util.Timer#scheduleAtFixedRate(java.util.TimerTask,long,long)
*/
public void setScheduledTimerTasks(ScheduledTimerTask[] scheduledTimerTasks) {
this .scheduledTimerTasks = scheduledTimerTasks;
}
/**
* Set whether the timer should use a daemon thread,
* just executing as long as the application itself is running.
*
Default is "false": The timer will automatically get cancelled on
* destruction of this FactoryBean. Hence,if the application shuts down,
* tasks will by default finish their execution. Specify "true" for eager
* shutdown of threads that execute tasks.
* @see java.util.Timer#Timer(boolean)
*/
public void setDaemon( boolean daemon) {
this .daemon = daemon;
}
public void afterPropertiesSet() {
logger.info( "Initializing Timer" );
this .timer = createTimer( this .daemon);
// Register all ScheduledTimerTasks.
if ( this .scheduledTimerTasks != null ) {
for ( int i = 0 ; i < this .scheduledTimerTasks.length; i++) {
ScheduledTimerTask scheduledTask = this .scheduledTimerTasks[i];
if (scheduledTask.getPeriod() > 0 ) {
// repeated task execution
if (scheduledTask.isFixedRate()) {
this .timer.scheduleAtFixedRate(
scheduledTask.getTimerTask(),scheduledTask.getDelay(),
scheduledTask.getPeriod());
}
else {
this .timer.schedule(
scheduledTask.getTimerTask(),scheduledTask.getDelay(),
scheduledTask.getPeriod());
}
}
else {
// One-time task execution.
this .timer.schedule(scheduledTask.getTimerTask(),
scheduledTask.getDelay());
}
}
}
}
/**
* Create a new Timer instance. Called by afterPropertiesSet.
* Can be overridden in subclasses to provide custom Timer subclasses.
* @param daemon whether to create a Timer that runs as daemon thread
* @return a new Timer instance
* @see #afterPropertiesSet()
* @see java.util.Timer#Timer(boolean)
*/
protected Timer createTimer( boolean daemon) {
return new Timer(daemon);
}
public Object getObject() {
return this .timer;
}
public Class getObj
|