Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Timer servlet in apache tomcat problem...help

Posted on 2003-03-03
16
Medium Priority
?
1,228 Views
Last Modified: 2012-06-22
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 !!!
0
Comment
Question by:bob_jones12
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
16 Comments
 
LVL 14

Expert Comment

by:kennethxu
ID: 8058284
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 );
          }
     }
}
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8058288
let me know if you have further enquires.
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8058493
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;
                    }
               }
          }
     }
}
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 28

Expert Comment

by:rrz
ID: 8058755
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
       }
}
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8059685
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;
                    }
               }
          }
     }
}
0
 
LVL 92

Accepted Solution

by:
objects earned 800 total points
ID: 8060996
No need to worry about threads as Java already includes a Timer class:

import java.util.Timer;
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
{
    private static final HOUR = 60 * 60 * 1000;

    private Timer timer = new Timer(true);

    public void init()
    {
       timer.scheduleAtFixedRate(new MyTimerTask(), HOUR, HOUR);
    }

    public void destroy()
    {
       timer.cancel();
    }

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


And create the task to run as a subclass of TimerTask:

import java.util.TimerTask;

public class MyTimerTask extends TimerTask
{
   public void run()
   {
      // do your task here
   }
}
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8064669
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.
0
 
LVL 92

Expert Comment

by:objects
ID: 8069650
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?
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8077144
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.
0
 
LVL 92

Expert Comment

by:objects
ID: 8077194
I can't imagine there could have been a problem as it has no reason to use Timezone (or related class).
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8077259
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?
0
 
LVL 92

Expert Comment

by:objects
ID: 8077306
> 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.

0
 

Author Comment

by:bob_jones12
ID: 8080184
Thanks guys for taking the time to help me out.

i've implemented objects solution and it works fine.

Thanks
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8081368
glad to know you problem is solved.
0
 
LVL 92

Expert Comment

by:objects
ID: 8083780
> i've implemented objects solution and it works fine.

Can you accept my answer then so this question can be PAQ'ed. Thanks :)
0
 
LVL 92

Expert Comment

by:objects
ID: 8091458
Thanks for that :-)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Whoever said that “a picture is worth one thousand words” observed a fact that can dramatically affect your marketing success. Most people tend to learn visually, so many publishers commonly acknowledge the effectiveness of visual learning by using…
The core idea of this article is to make you acquainted with the best way in which you can export Exchange mailbox to PST format.
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

704 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question