tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Terence M. Bandoian" <tere...@tmbsw.com>
Subject Re: Terminating Timer Thread Gracefully
Date Thu, 14 Jul 2011 05:05:24 GMT
  On 1:59 PM, Pid wrote:
>
> ATimerTask is a private instance in AServletContextListener, is this
> necessary and if so, why?
>
> What logic is contained in ATimerTask?
>
> Are you overriding TimerTask.cancel() and do you catch InterruptedException?
>
>
> p

Hi, Pid-

For the sake of clarity, I'll repeat this here:

public class AServletContextListener implements ServletContextListener
{
     private Timer timer;
     private ATimerTask timerTask;

     public AServletContextListener()
     {
     }

     public void contextInitialized( ServletContextEvent sce )
     {
         if ( timer == null )
         {
             Calendar firstRunTime;

             timer = new Timer( true );
             timerTask = new ATimerTask();

             firstRunTime = new GregorianCalendar();
             firstRunTime.set( Calendar.HOUR_OF_DAY, 12 );
             firstRunTime.set( Calendar.MINUTE, 0 );
             firstRunTime.set( Calendar.SECOND, 0 );
             firstRunTime.set( Calendar.MILLISECOND, 0 );

             timer.scheduleAtFixedRate(
                 timerTask, firstRunTime.getTime(), 1000 * 60 * 60 * 24 );
         }
     }

     public void contextDestroyed( ServletContextEvent sce )
     {
         if ( timer != null )
         {
             timer.cancel();
             timer.purge();

             timer = null;
             timerTask = null;

             try
             {
                 Thread.sleep( 1000 );
             }
             catch ( InterruptedException ie )
             {
             }
         }
     }
}

It isn't absolutely necessary but why would I make the ATimerTask 
reference anything but private?

The timer tasks in the application perform some very straightforward 
database and file system maintenance when their run methods are invoked 
that might take up to half a second each.  None override the cancel 
method.  All are scheduled to execute on a daily or weekly basis and 
none at even close to the same time of day.

Also, while testing for ways to prevent the error message from being 
written to the logs, I commented out the run method bodies of the timer 
tasks so that they returned immediately and, given that I know the 
schedule, none of the timer tasks were executing when I stopped or 
restarted Tomcat.

The InterruptedException is caught and logged if it occurs.  I've never 
seen it in the logs.

Thanks.

-Terence


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org


Mime
View raw message