Link to home
Start Free TrialLog in
Avatar of bob_jones12
bob_jones12

asked on

Timer servlet in apache tomcat problem...help

Hello

I am trying to write a timer servlet that starts up when tomcat is started up (set up in the web.xml file to <load-on-startup>) and runs a single method once an hour.

I'm new to this technology and havent got time to learn everything to do this one task. Basically i havent got a clue on to slove this problem.  

I would be gateful if anyone could provide an example of a timer servlet and how to initalise it in tomcat.  Does not need to be specific to my problem, i can use the example as a basis to solve my problem

Thank You for any help !!!
Avatar of kennethxu
kennethxu

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

public final class MyServlet extends HttpServlet implements Runnable {
    private static boolean stopTimer = false;

     public void init()
     {
          new Thread( this ).start();
     }

     public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException
     {
     }

     public void run()
     {
          while( ! stopTimer ) {
               // call the method
               Thread.sleep( 1000 * 3600 );
          }
     }
}
let me know if you have further enquires.
more accurately, i'd suggest this:

=================
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

public final class TimerServlet extends HttpServlet implements Runnable {
    private static boolean stopTimer = false;

     public void init()
     {
          new Thread( this ).start();
     }

     public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException
     {
     }

     public void run()
     {
          long interval = 3600 * 1000;
          long timer = System.currentTimeMillis();
          while( ! stopTimer ) {
               // call the method
               System.out.println( "timer servlet: calling method" );
               timer += interval;
               while( true ) {
                    try {
                         Thread.sleep( timer - System.currentTimeMillis() );
                         break;
                    } catch( java.lang.InterruptedException e ) {
                         continue;
                    }
               }
          }
     }
}
Avatar of rrz
If you are using Servlet 2.3 API,
then how about using a listener instead of a servlet?

import javax.servlet.*;
public class MyListener implements ServletContextListener{
       public void contextInitialized(ServletContextEvent sce){
                //start thread
       }
       public void contextDestroyed(ServletContextEvent sce){
               //stop thread
       }
}
It's a good point that we'd better to give the thread an end point, this code will properly end timer thread when server goes down.
======================
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class TimerServlet extends HttpServlet implements Runnable {
    private static boolean stopTimer = false;
     private static Thread timerThread = null;

     public void init()
     {
          timerThread = new Thread( this );
          timerThread.start();
     }

     public void destroy()
     {
          stopTimer = true;
          timerThread.interrupt();
          Thread.yield();
     }

     public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException
     {
     }

     public void run()
     {
          long interval = 3600 * 1000;
          long timer = System.currentTimeMillis();
          while( ! stopTimer ) {
               // call the method
               System.out.println( "timer servlet: calling method" );
               timer += interval;
               while( true ) {
                    try {
                         Thread.sleep( timer - System.currentTimeMillis() );
                         break;
                    } catch( java.lang.InterruptedException e ) {
                         if( stopTimer ) break;
                         else continue;
                    }
               }
          }
     }
}
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
object, I heard that the java.util.Timer class has a bug when system time adjust from and to daylight saving time. do you know if it's been fixed in jdk1.4? thanks.
The timezone is not used by the Timer class so I cannot see how such a problem could occur, unless the PC clock is being adjusted. In which case your code would have the same problem (as would lots of things) :)

Do you have a referecne to the bug report?
there are 35 items in Bug Parage related to java.util.Timer, I cannot find the one I mentioned and that's why asking. I came across it somewhere when 1.3 was first released, cannot find any link now.
I can't imagine there could have been a problem as it has no reason to use Timezone (or related class).
not so sure, may be related to other schedule method which take Date as parameter. you comment also force me to re-visit api doc and I find:

Fixed-delay execution is appropriate for recurring activities that require "smoothness." In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run.

Frankly, I don't quite sure what it try to imply, any idea?
> may be related to other schedule method which take Date as parameter.

Date is not affected by Timezone.

> any idea?

With things like animations it is important to schedule recurring tasks wrt to the previous task, as opposed to the first task which is important for things like alarms.

Avatar of bob_jones12

ASKER

Thanks guys for taking the time to help me out.

i've implemented objects solution and it works fine.

Thanks
glad to know you problem is solved.
> i've implemented objects solution and it works fine.

Can you accept my answer then so this question can be PAQ'ed. Thanks :)
Thanks for that :-)