views:

317

answers:

3

I have a J2EE application that has two components: First is a service that scrapes some information from internet and fills it into database. Second is a web interface (deployed on tomcat) from where user can browse that information.

What could be the best approach to implement the first component? Should it be run as a background Daemon/Service or a thread within the container?

+6  A: 

I would personally separate them into different processes. Aside from anything else, it means you can restart one without worrying about the other. It also means you can really easily deploy them on different machines without pointlessly installing Tomcat for a service which doesn't actually need a web interface.

Jon Skeet
do u think that java.util.Timer and java.util.TimerTask classes can used for this purpose? Thanks
craftsman
The Spring scheduling classes I mentioned in my answer provide a good interface to the java concurrency objects, such as Executor, which is really what you should be using in a modern application.
grkvlt
+2  A: 

There is nothing wrong with having background jobs inside a web container, but you MUST let the web container know about it so it can be stopped and started properly.

Have a look at the load-on-startup tag in web.xml. There are some advice on http://wiki.metawerx.net/wiki/Web.xml.LoadOnStartup

Thorbjørn Ravn Andersen
+5  A: 

Depending on the type of application framework, Spring lets you use Quartz or the java.util.concurrent framework. Spring has a TaskExecutor abstraction (see the Spring documentation) which simplifies a lot of this, but check to see which fits best with your design.

Spring or Quartz (managed by Spring) then controls the creation and starting/stopping of Threads or Executors or Jobs, along with their frequency/period and other scheduling parameters, and also manages any pooling of jobs you might require.

I use these for all my background tasks and batch jobs in any J2EE applications I write with no problems. Since the jobs are Spring managed POJOs, they have access to the full dependency injection framework and so on that that Spring entails, and of course you can switch between scheduler frameworks with a simple change to you application configuration XML file as your needs change or scale.

grkvlt
+1 on quartz, I have used it in many j2ee applications to schedule background processes.
broschb