Java Servlet: starting a thread that always runs

  • when Java Servlet starts it reads web.xml
  • add listener implementation class to your web.xml



<display-name>your_servlet_namedisplay-name>

<listener>
<listener-class>com.your_package_name.TimedServletCallerlistener-class>
listener>

  • we will use ServletContextListener interface
  • create a NEW thread (Loop) inside contextInitialized(), if you did Thread.sleep without new thread the whole Servlet would pause and container would fail to start it after 45 seconds or so


public class TimedServletCaller implements ServletContextListener
{
private static int sleepMinutes = 1;

class Loop extends Thread
{
public void run()
{
while (true)
{
Log.e("Loop is running!");
takeShortNap();
// do stuff here
}
}
}

@Override
public void contextInitialized(ServletContextEvent arg0)
{
Log.e("***** TimedServletCaller.contextInitialized()");
// execute();
Thread thread = new Loop();
thread.start();
}

private static void takeShortNap()
{
Log.i(" Pausing for " + sleepMinutes + " minute(s).");
try
{
Thread.sleep(sleepMinutes * 60 * 1000);
catch (InterruptedException e)
{
Log.e(e.getMessage());
}
}

  • restart your server (Tomcat) now you can use your Servlet, but also the Loop keeps running and doing useful things like database updates, etc.


As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles