Friday, June 25, 2010

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.