views:

94

answers:

3

Hi, I'm developing JSP/Servlets App,and I want to execute a service at a specific time , for example :

For each day at 10:00 AM , delete any attachment from the "attachment" table in the database where column X== NULL.

How can I do this in JSP/Servlets application ? I use Glassfish as a server .

+3  A: 

You are running on a glassfish JEE server so you should have access to the EJB Timer service.

Here is an example :

http://java-x.blogspot.com/2007/01/ejb-3-timer-service.html

I used the previous version of the API on JBoss, and that worked fine.

Currently we tend to drop Quartz in the war and use that for timed executions, so it also works on our Jetty development instances

Peter Tillemans
+1  A: 

You need to check if the server implementation used supports firing tasks like this. If it doesn't support it or you'd like to be server independent, then implement a ServletContextListener to hook on webapp's startup and use ScheduledExecutorService to execute a task at the given time and intervals.

Here's a basic kickoff example:

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();
    }

}

Where Task implements Callable and millisToNext1000 is the amount of millis to next 10:00 AM. You can use Calendar or JodaTime to calculate it. As a non-Java-standard alternative, you can also consider to use Quartz.

BalusC
+1  A: 

Implement ServletContextListener ; in the contextInitialized method :

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 ());
}

Edit your web.xml to have reference to your listener implementation:

<listener>
   <listener-class>your.package.declaration.MyServletContextListener</listener-class>
</listener>
ring bearer
thanks @ring , @Balus , @Peter , All your answers are useful ,and I run an example successfully, but I have to choose one answer :( , I chose @ring answer because he added the last line , Listener-class . Thanks guys.
BugKiller