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?
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
curlfromcrontab).ServletContextListeneris the preferred method these days; Servlet’sinit()was an OK method back whenServletContextListenerwasn’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.