Hi, I want to perform a certain activity on regular intervals like 3 months or 6 months. This activity should get fired automaticaly and should create a activity log with any manual intervention. I am not quite sure how to implement it using thread. I am planning to a low priority thread which sleeps most of the time and then check last_action time from database if it > 3 months then start a activity. Is theer any other efficient way of implementing it ?
There are scheduling packages to do this for you like Quartz and Flux. I can't say I'd recommend Flux (have not used the latest versions) and I have no hands on with Quartz.
If I had to do it all on my own, I'd probably do something at JVM startup (don't know if this is a server, desktop app or what) to get the next scheduled task from the database and create a Timer to go off at the scheduled time. When the task is completed, update the database to delete it or show it done, get the next scheduled event and so on.
What happens if you schedule a new tasks before the "next" in memory? Say the next task I got from the database was for 4:00 and at noon I schedule one for 3:00. The update process might cancel the existing timer and start a new one.
This gets trickier yet in a cluster. You need to assure only one server in a cluster does each job, recover from one shutting down before doing its next task, and much more. In clusters Flux uses polling intead of timers. Every so often a server gets the next item from database and marks it in progress. This is within a transaction with read for update so only one server can get an item. When the task is done it deletes the task from database.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Thanks for the reply. Yes, we can use Timer/Timertask and Thread or we can use Unix daemon/cron utility to do it. My application is a web app, this regular activity is a small activity which is a part of this webapp and has to be fired automaticaly every 3 months a kind of report generation and data integrity check for the webapp. As its part of a bigger application I can't go for daemon/cron job, This activity will be failrly time consuming so I am bit confused to use Timertask. I am however trying to use Quartz along with the my struts framework by going through an article on onjava, but till now no luck.