【发布时间】:2011-03-01 09:44:40
【问题描述】:
我正在开发 JSP/Servlets App,我想在特定的时间执行一个服务,例如:
对于每天上午 10:00,删除任何 “附件”表中的附件 在列 X== NULL 的数据库中。
如何在 JSP/Servlets 应用程序中做到这一点? 我使用 Glassfish 作为服务器。
【问题讨论】:
标签: java servlets scheduled-tasks
我正在开发 JSP/Servlets App,我想在特定的时间执行一个服务,例如:
对于每天上午 10:00,删除任何 “附件”表中的附件 在列 X== NULL 的数据库中。
如何在 JSP/Servlets 应用程序中做到这一点? 我使用 Glassfish 作为服务器。
【问题讨论】:
标签: java servlets scheduled-tasks
您在 glassfish Java EE 服务器上运行,因此您应该可以访问 EJB Timer 服务。
这是一个例子:
http://java-x.blogspot.com/2007/01/ejb-3-timer-service.html
我在 JBoss 上使用了以前版本的 API,效果很好。
目前我们倾向于在战争中放弃 Quartz 并将其用于定时执行,因此它也适用于我们的 Jetty 开发实例
【讨论】:
您需要检查使用的服务器实现是否支持这样的触发任务。如果它不支持它或者你想独立于服务器,那么实现一个ServletContextListener 来挂钩 webapp 的启动并使用ScheduledExecutorService 在给定的时间和间隔执行任务。
这是一个基本的启动示例:
public class Config implements ServletContextListener {
private ScheduledExecutorService scheduler;
public void contextInitialized(ServletContextEvent event) {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Task(), millisToNext1000, 1, TimeUnit.DAYS);
}
public void contextDestroyed(ServletContextEvent event) {
scheduler.shutdown();
}
}
其中Task 实现Callable 和millisToNext1000 是到下一个上午10:00 的毫秒数。您可以使用Calendar 或JodaTime 来计算它。作为非 Java 标准的替代方案,您还可以考虑使用Quartz。
【讨论】:
实现ServletContextListener;在contextInitialized 方法中:
ServletContext servletContext = servletContextEvent.getServletContext();
try{
// create the timer and timer task objects
Timer timer = new Timer();
MyTimerTask task = new MyTimerTask(); //this class implements Callable.
// get a calendar to initialize the start time
Calendar calendar = Calendar.getInstance();
Date startTime = calendar.getTime();
// schedule the task to run hourly
timer.scheduleAtFixedRate(task, startTime, 1000 * 60 * 60);
// save our timer for later use
servletContext.setAttribute ("timer", timer);
} catch (Exception e) {
servletContext.log ("Problem initializing the task that was to run hourly: " + e.getMessage ());
}
编辑您的 web.xml 以引用您的侦听器实现:
<listener>
<listener-class>your.package.declaration.MyServletContextListener</listener-class>
</listener>
【讨论】: