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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With