Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Servlets : "best practice" for running background tasks? [duplicate]

I'm working on a web application which needs to clear expired cache elements now and then. I'd like to do this using the Quartz framework, and have a separate job to take part of this.

Now, I've used Quartz in other projects and usually schedule all jobs from a ServletContextListener using contextInitialised(ServletContextEvent sce) and contextDestroyed(ServletContextEvent sce). However, I've done it this way because a tutorial i once read did it that way.

I'm uncertain if I can just schedule the tasks from the servlet's init() and destroy() methods instead? I guess one could argue that I'm now mixing background tasks and servlets, and thus responsibilities, but I'd like to hear if there is a "best practice" on this?

like image 789
sbrattla Avatar asked Dec 04 '11 13:12

sbrattla


2 Answers

First of all, usual disclaimer: you're not supposed to mess with threads in a Servlet container. So all the ways are by definition wrong (I suspect the right way would be calling curl from crontab).

ServletContextListener is the preferred method these days; Servlet's init() was an OK method back when ServletContextListener wasn't here. There are different problems with servlets, though: first of all, it may not be inited on startup (addressed by load-on-startup parameter); it can be unloaded just because servlet contained decided to do so (never saw in practice—but the spec says it can be).

Most important, though, is that it's a trick—and as any other trick, it makes little sense to the reader unless you document it carefully, or he knows well ahead that it's a trick. So if in doubt, avoid.

like image 191
alf Avatar answered Sep 29 '22 18:09

alf


A servlet is not necessarily initialized when the webapp is deployed. It may be initialized lazily.

And you may have many servlets in a single webapp, so you might then wonder which servlet would be responsible of the scheduling.

A ServletContextListener is the right tool to use when something must be done at deployment and undeployment time.

like image 35
JB Nizet Avatar answered Sep 29 '22 20:09

JB Nizet