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:
- Clean up some data from the data base every hour
- 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?
You can use
ServletContextListenerto execute some initialization on webapp’s startup. The standard Java API way to run periodic tasks would be a combination ofTimerandTimerTask. Here’s a kickoff example:where the both tasks can look like:
Using
Timeris however not recommended in Java EE. If the task throws an exception, then the entireTimerthread is killed and you’d basically need to restart the whole server to get it to run again. TheTimeris also sensitive to changes in system clock.The newer and more robust
java.util.concurrentway would be a combination ofScheduledExecutorServiceand just aRunnable. Here’s a kickoff example: