I’m using Java and I want to keep a servlet continuously running in my application, but I’m not getting how to do it. My servlet has a method which gives counts of the user from a database on a daily basis as well as the total count of the users from the whole database. So I want to keep the servlet continuously running for that.
Share
Your problem is that you misunderstand the purpose of the servlet. It’s intented to act on HTTP requests, nothing more. You want just a background task which runs once on daily basis.
EJB available? Use
@ScheduleIf your environment happen to support EJB (i.e. a real Java EE server such as WildFly, JBoss, TomEE, Payara, GlassFish, etc), then use
@Scheduleinstead. Here are some examples:Yes, that’s really all. The container will automatically pickup and manage it.
EJB unavailable? Use
ScheduledExecutorServiceIf your environment doesn’t support EJB (i.e. you’re not using not a real Java EE server, but a barebones servletcontainer such as Tomcat, Jetty, etc), then use
ScheduledExecutorService. This can be initiated by aServletContextListener. Here’s a kickoff example:Where the job classes look like this:
Do not ever think about using
java.util.Timer/java.lang.Threadin a Java EE / Servlet based environmentLast but not least, never directly use
java.util.Timerand/orjava.lang.Threadin Java EE. This is recipe for trouble. An elaborate explanation can be found in this JSF-related answer on the same question: Spawning threads in a JSF managed bean for scheduled tasks using a timer.