如何使用 JSP/Servlet 应用程序在特定时间运行服务?

Abd*_*lah 5 java servlets scheduled-tasks

我正在开发JSP/Servlets应用程序,我想在特定时间执行服务,例如:

每天上午 10:00,从数据库中“附件”表中删除其中 X== NULL 列的任何附件。

我如何在 JSP/Servlet 应用程序中执行此操作?我使用 Glassfish 作为服务器。

rin*_*rer 2

实施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 ());
}
Run Code Online (Sandbox Code Playgroud)

编辑您的 web.xml 以引用您的侦听器实现:

<listener>
   <listener-class>your.package.declaration.MyServletContextListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)