This forum is now a read-only archive. All commenting, posting, registration services have been turned off. Those needing community support and/or wanting to ask questions should refer to the Tag/Forum map, and to http://spring.io/questions for a curated list of stackoverflow tags that Pivotal engineers, and the community, monitor.

background threads in Spring application?

Dec 5th, 2011, 04:34 AM

Folks;
currently I try integrating Apache CouchDB change notifications into our Spring webapp. The idea, generally, is to have a long-running HTTP GET request to the CouchDB backend from some Java client class which, therefore, also is a long-running thread (to start with the application context and to terminate with the application context being terminated) providing some sort of event handlers invoked whenever there's some change in the CouchDB database structure.

At the moment, I try to find the most "clean" way how to include this into the Spring application. My initial attempt was to introduce a ServletContextListener to create (and run) an instance of this monitoring thread, however, this seems pretty much outside Spring.

The second idea was "just" to create a pretty much standard Spring bean which starts (and runs) the CouchDB "watcher" thread either in its constructor or in some method triggered once, in example, by a SimpleTriggerBean.

Looking around, however, I am not sure which of these approaches (if any) is the one I would want to go for, or whether there are more sane ways of dealing with this setup. So, how would you add a feature like this one (a "background" thread starting at context startup and terminating with context shutdown) into your Spring app?

Any input on this greatly welcome. Thanks in advance and all the best,
Kristian

I will definitely try this in order to ease our task configuration in other parts of the system, but then again, I am unsure how this fits my current use case - actually, I would want to have a long-running background task that starts with the context being started and is terminated with the context being terminated. The use case itself is to have this task continuously connected to the backend system (HTTP long polling) and handle incoming events so regular scheduled tasks don't seem the way to go here. Can I use the <task:> stuff to have a task that just runs _once_ with a given delay after the context has been started? This would help IMHO.