Short question: Within a Tomcat 6 app - how can I run a (separate) thread-pool?
What is the best solution for running a thread pool?
For your use case, you can utilize Timer and TimerTask available in java platform to execute a background task periodically.
import java.util.Timer;
import java.util.TimerTask;
TimerTask dbTask = new TimerTask() {
@Override
public void run() {
// Perform Db call and do some action
}
};
final long INTERVAL = 1000 * 60 * 5; // five minute interval
// Run the task at fixed interval
new Timer(true).scheduleAtFixedRate(dbTask, 0, INTERVAL);
Note, if a task takes more than five minutes to finish, subsequent tasks will not be executed in parallel. Instead they will wait in the queue and will be executed rapidly one after another when the previous one finishes.
You can wrap this code in a singleton class and invoke from the startup servlet.
Generally, its a good practice to perform these kinds of periodic background jobs outside of Servlet containers as they should be efficiently used serve HTTP requests.