19

I have developed a web application using using servlet and JSP. I am not using any framework per se, instead using my own home brewed MVC framework. I am using MySQL as a backend.

I want to do the following:

  1. Clean up some data from the data base every hour
  2. Generate and store statistics about data every 15 minutes in an XML file somewhere

The problem is: currently all my code runs as a result of the request received from a client.

How do I run periodic task(s) at the server side?

One solution I have right now is to creare a thread in the controller's init function. Are there any other options?

Michael Currie
  • 11,166
  • 7
  • 39
  • 54
jsshah
  • 1,701
  • 1
  • 10
  • 18

2 Answers2

41

You can use ServletContextListener to execute some initialization on webapp's startup. The standard Java API way to run periodic tasks would be a combination of Timer and TimerTask. Here's a kickoff example:

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

where the both tasks can look like:

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

Using Timer is however not recommended in Java EE. If the task throws an exception, then the entire Timer thread is killed and you'd basically need to restart the whole server to get it to run again. The Timer is also sensitive to changes in system clock.

The newer and more robust java.util.concurrent way would be a combination of ScheduledExecutorService and just a Runnable. Here's a kickoff example:

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();
}
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • 2
    Just want to add to BalusC's fantastic answer that `ScheduledExecutorService`'s `scheduleAtFixedRate` and `scheduleWithFixedDelay` methods will suppress future executions if exception was encountered in a run. So remember to handle your exceptions. `If any execution of the task encounters an exception, subsequent executions are suppressed.` – dvd Jun 01 '12 at 00:49
2

you can use any schedular to schedule your process like quartz, spring scheduler

http://static.springsource.org/spring/docs/2.5.x/reference/scheduling.html has a good support for these stuffs with any implementation.

Puran
  • 964
  • 6
  • 15