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