views:

716

answers:

5

What's the best/easiest way to run periodic tasks (like a daemon thread) on a tomcat/jetty server? How do I start the thread? Is there a simple mechanism or is this a bad idea at all?

+2  A: 

One general purpose way which works for many systems is simply to have a cron job which performs a periodic wget against your app.

Paul Dixon
Just run a cron job on the server, no need to have it perform a wget against your app.
Ryan Guest
A: 

I can't answer the tomcat/jetty stuff, but I've done similar things with Python based web apps.

I normally just run a separate app that does the periodic tasks needed. If interop is needed between the website and the app, that communication can happen through some sort of API (using something like XML-RPC/unix sockets/etc) or even just through the database layer, if that's adequate.

Hope that helps.

Eddie Parker
+8  A: 

If want to keep everything on java side, give a look to Quartz.
It handles failover and fine grained repartition of jobs, with the same flexibility of cron jobs.

MatthieuP
The Quartz framework being Java also integrates directly into your running application server and gives you fine grained control which you would otherwise struggle to achieve from Java with Cron
j pimmel
quartz sounds good, but a bit of an overkill for my purpose.
Harald Schilly
+2  A: 

It's okay and effective to stash a java.util.Timer (or better yet ScheduledExecutor) instance in your ServeletContext. Create it in a Servlet's init() call and all your servlets can add TimerTasks to it.

Ry4an
ok, good, that's something i had in mind but i was curious if there is a special mechanism ;)
Harald Schilly
A: 

If you want to use a cron job but don't have administrative access to the development system, you can do a user crontab by executing the command:

crontab -e

It uses vi by default on most systems, but you can change it to the editor of your choice via:

export EDITOR=/usr/local/bin/my_editor

Then, executing the crontab -e command will launch your crontab file in your editor. Upon saving, the changes will be committed back into the system's cron.

Nolte Burke