Issue
Have to call the servlet periodically.(like service concept in andorid)
How to do this. Using timer or any other solution?
Thanks in advance.
Solution
To expand on the comments by JB Nizet…
The formerly accepted answer is kind of a hack. If the goal is to get some regular task to be performed as part of your web app, Java provides a crew slick technologies to make this happen.
ServletContextListener
The first is a hook defined by the Servlet spec to have code invoked when a web app is deployed and when a web app is shutting down. This hook is the ServletContextListener.
ScheduledExecutorService
The second piece is the executor service added to recent versions of Java as a more sophisticated alternative to the old Timer class. In particular you need the ScheduledExecutorService.
So when your web app start up, the ServletContextListener launches a ScheduledExecutorService. When the ServletContextListener is informed of a shutdown, it tells the executor to gracefully quit.
One trick to this: Be sure to capture all exceptions in your executor. If an exception leaks, the executor silently stops executing. This is a feature not a bug. Read the doc and study up with some googling.
Jakarta Concurrency
Some Servlet containers support Jakarta Concurrency. This specification provides for automatic management of the executor services discussed above.
Answered By - Basil Bourque
Answer Checked By - David Marino (JavaFixing Volunteer)