专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »Java教程 » spring定时任务:彻底理解Spring的定制任务 »正文

spring定时任务:彻底理解Spring的定制任务

来源: 发布时间:星期四, 2009年1月8日 浏览:14次 评论:0
  相信做软件Software朋友都有这样经历软件Software是不是少了点什么东西呢?比如定时任务啊!就拿新闻发布系统来说如果新闻数据更新太快势必涉及个问题这些新闻不能由人工去发布应该让系统自己发布这就需要用到定时定制任务了以前定制任务无非就是设计个Thread并且设置运行时间片让它到了那个时间执行就ok了让系统启动时候启动它想来也够简单不过有了spring我想这事情就更简单了   看看spring配置文件想来就只有这个配置文件了

  XML代码:

< bean  id = "infoCenterAutoBuildTask"  
= "com.teesoo.teanet.scheduling.InfoCenterAutoBuildTask" >  
< property  name = "baseService"  ref = "baseService"  />  
< property  name = "htmlCreator"  ref = "htmlCreator"  />  
  
< bean  id = "scheduledTask"  
= "org.springframework.scheduling.timer.ScheduledTimerTask" >  
  
< property  name = "delay"  value = "10000"  />  
  
< property  name = "period"  value = "1000000"  />  
< property  name = "timerTask"  ref = "infoCenterAutoBuildTask"  />
   
< bean  id = "timerFactory" 
= "org.springframework.scheduling.timer.TimerFactoryBean" >  
< property  name = "scheduledTimerTasks" >  
< list >  
  
< ref  bean = "scheduledTask"  />  
  上面 3个配置文件中只有个配置文件是涉及到您自己其他都是spring很简单吧!

  我们只需要涉及让他继承java.util.TimerTask;

  Java代码:

BaseTask extends java.util.TimerTask {  
//用户只需要实现这个方面把自己任务放到这里  
public  void run{  
}  
}
  下面让我们来看看spring源代码:

  Java代码:

/* 
* Copyright 2002-2005 the original author or authors. 
*  
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
*  
*   http://www.apache.org/licenses/LICENSE-2.0 
*  
* Unless required by applicable law or agreed to in writing, software 
* distributed under the License is distributed _disibledevent= this .scheduledTimerTasks[i];  
 (scheduledTask.getPeriod > 0 ) {  
// repeated task execution  
 (scheduledTask.isFixedRate) {  
this .timer.scheduleAtFixedRate(  
scheduledTask.getTimerTask, scheduledTask.getDelay,
scheduledTask.getPeriod);  
}  
 {  
this .timer.schedule(  
scheduledTask.getTimerTask, scheduledTask.getDelay,
scheduledTask.getPeriod);  
}  
}  
 {  
// One-time task execution.  
this .timer.schedule(scheduledTask.getTimerTask,
scheduledTask.getDelay);  
}  
}  
}  
}  
/** 
* Create a Timer instance. Called by afterPropertiesSet. 
* Can be overridden in subes to provide custom Timer subes. 
* @param daemon whether to create a Timer that runs as daemon thread 
* @ a Timer instance 
* @see #afterPropertiesSet 
* @see java.util.Timer#Timer(boolean) 
*/  
protected Timer createTimer( boolean daemon) {  
   Timer(daemon);  
}   
public Object getObject {  
  this .timer;  
}  
public Class getObjectType {  
 Timer. ;  
}  
public  boolean isSingleton {  
  true ;  
}   
/** 
* Cancel the Timer on bean factory shutdown, stopping all scheduled tasks. 
* @see java.util.Timer#cancel 
*/  
public  void destroy {  
logger.info( "Cancelling Timer" );  
this .timer.cancel;  
}   
}
  这个类就是运行我们任务类了我们可以定制N个任务只需要塞到这里就ok了

0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: