在服务器端为servlet JSP MVC网站运行定期任务

我使用servlet和JSP开发了一个Web应用程序。 我本身并没有使用任何框架,而是使用我自己的自制的MVC框架。 我使用MySQL作为后端。

我想做以下事情:

  1. 每小时清理数据库中的一些数据
  2. 在某个XML文件中每15分钟生成并存储有关数据的统计信息

问题是:目前我的所有代码都是从客户端收到的请求运行的。

如何在服务器端运行定期任务?

我现在的一个解决方案是在控制器的init函数中创建一个线程。 还有其他选择吗?

您可以使用ServletContextListener在webapp的启动时执行一些初始化。 运行定期任务的标准Java API方式是TimerTimerTask的组合。 这是一个启动示例:

 public void contextInitialized(ServletContextEvent event) { Timer timer = new Timer(true); timer.scheduleAtFixedRate(new CleanDBTask(), 0, oneHourInMillis); timer.scheduleAtFixedRate(new StatisticsTask(), 0, oneQuartInMillis); } 

两个任务的位置如下:

 public class CleanDBTask extends TimerTask { public void run() { // Implement. } } 

但是,在Java EE中不建议使用Timer 。 如果任务抛出exception,那么整个Timer线程都会被终止,你基本上需要重启整个服务器才能让它再次运行。 Timer对系统时钟的变化也很敏感。

更新更强大的java.util.concurrent方法将是ScheduledExecutorServiceRunnable的组合。 这是一个启动示例:

 private ScheduledExecutorService scheduler; public void contextInitialized(ServletContextEvent event) { scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new CleanDBTask(), 0, 1, TimeUnit.HOURS); scheduler.scheduleAtFixedRate(new StatisticsTask(), 0, 15, TimeUnit.MINUTES); } public void contextDestroyed(ServletContextEvent event) { scheduler.shutdownNow(); } 

您可以使用任何计划来安排您的过程,如石英,弹簧调度程序

任何实现http://static.springsource.org/spring/docs/2.5.x/reference/scheduling.html都对这些东西有很好的支持。