views:

437

answers:

6

My experience with application servers is limited to some basic servlet coding, so I am not even sure how to frame this question appropriately.

I need to write a java program that runs on the (java) application server and continuously executes a certain method (it will check for files in a certain directory).

I have found a way to schedule the start of applications but need to know where to put the code that I would normally put in the main() method in a regular java program.

+1  A: 

Take a look at the servlet event listeners.

I think you should be able to hook into your code using a ServletContextListener.

http://onjava.com/pub/a/onjava/2001/04/12/listeners.html

pjp
+1  A: 

You can use Quartz, or the EJB timer service (if you can learn EJBs) for this task.

If you have just a servlet container like Tomcat, it is preferable to go with Quartz. In fact, Quartz also comes with a web application to monitor a scheduler.

On the other hand, the EJB timer service is available in all EJB containers that support EJB 2.1 and above.

Vineet Reynolds
+2  A: 

Not answering straight to your question, but check out Spring Batch that could be useful.

Touko
A: 

One way of doing this is to write a Listener which implements ServletContextListener and you write you schedule your timer in contextInitialized method

A: 

You MUST let the web container manage your threads!

Read the specification for web.xml carefully - what you need is in there.

Thorbjørn Ravn Andersen
Why? It is quite common to start your own threads in java web applications. What's wrong with that?
Peter Štibraný
To let the container know what resources are being used. If you start threads yourself it is your responsibility to tear them down _properly_. This may influence a containers ability to migrate an web application to another node or similar.
Thorbjørn Ravn Andersen
Thanks for explanation, that makes sense. It's good idea to be careful with threads (but it wouldn't stop me from creating new ones when needed).
Peter Štibraný