spring定时器

想用SPRING定时器,来定时读取数据库中的数据。然后把数据放到ServletContext application 中,想问下应该怎么来构建?

复杂定时任务建议使用Quartz,简单定时任务可使用如下方法:
首先在web.xml文件中配置一个监听器:


xxx.xxx.TaskService

然后在你的业务层定义这个类实现ServletContextListener接口:

java 代码:
public class TaskService implements ServletContextListener {
private Timer timer;
/**
* 计数初始化延迟时间
/
int minutesPassed = 5;
long initialDelay = getTomorrowTimeInMinute(minutesPassed) - System.currentTimeMillis();
/
*

* 在Web应用启动时初始化任务

*/

public void contextInitialized(ServletContextEvent event) {

timer = new Timer("从服务器下载处理后的日志文件",true);

timer.schedule(new BackUpTableTask(),0,24*3600*1000);

}

 /**  
  * 在Web应用结束时停止任务  
  */  
 public void contextDestroyed(ServletContextEvent event) {   
     timer.cancel(); // 定时器销毁   
    }

    最后,在BackUpTableTask()这个类中实现你的具体数据库查询逻辑以及将数据放到ServletContext中。

希望对你有帮助。

这里有篇文章可以参考一下!
http://www.iteye.com/topic/335371

如果业务比较复杂,建议使用Quartz,配置起来更方便!
http://www.iteye.com/topic/171245

希望对你解决问题有些帮助,呵呵! :D