我正在开发JSP / Servlets App,我想在特定时间执行服务,例如:
对于每天上午10:00,删除任何 来自“附件”表的附件 在数据库中,列X == NULL。
如何在JSP / Servlets应用程序中执行此操作? 我使用Glassfish作为服务器。
答案 0 :(得分:4)
您正在使用Glassfish Java EE服务器,因此您应该可以访问EJB Timer服务。
以下是一个例子:
http://java-x.blogspot.com/2007/01/ejb-3-timer-service.html
我在JBoss上使用了以前版本的API,并且运行正常。
目前我们倾向于在战争中放弃Quartz并将其用于定时执行,因此它也适用于我们的Jetty开发实例
答案 1 :(得分:3)
您需要检查所使用的服务器实现是否支持这样的触发任务。如果它不支持它或者您希望与服务器无关,那么实现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。
答案 2 :(得分:1)
实施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>