CMD Script: Automatic Restart TOMCAT

automatic restart tomcat There are times when you have to schedule tomcat to restart automatically for whatever reason. In my case, I have a Java web application using Hibernate, running on MySQL. Every so often the application will errored out with the ugly exception of stale connection. Sparing technicality of the exception, I am resorting to restart the tomcat everyday as an interim solution until I have worked out a better error handling routine.

My server environment:

WINDOWS 2K3 SERVER
TOMCAT 5.5.7
JAVA JDK 1.5.0

Tomcat as NT Service

you can easily restart the tomcat using following command.
net stop TOMCAT_SERVICE_NAME;
net start TOMCAT_SERVICE_NAME;

Tomcat in application mode

It gets a little complicated when you are managing Tomcat using the startup.bat/shutdown.bat batch script.

call shutdown.bat

call startup.bat

The above script will not work because Tomcat takes some time to shutdown completely. You’ll ended up with a new tomcat instance trying to start while the current one is still shutting down.

The idea here is to place a pause or wait cmd in between shutdown and startup script. But there is no PAUSE/WAIT/SLEEP command available for WinNT cmd.

Never fear. There is a quick way of simulating PAUSE / WAIT / SLEEP for N seconds command in batch script, that is by using the PING command.
ping 127.0.0.1

A PING command to localhost takes around 1 second to complete. So to pause for 30 seconds you can simply ping localhost 30 times
ping 127.0.0.1 -n 30

And here is the complete script to restart TOMCAT by calling the startup.bat/shutdown.bat.
@echo off

rem ------------------------------
rem shutdown tomcat
rem ------------------------------
call shutdown.bat

rem ------------------------------
rem wait 30 sec
rem ------------------------------
@ping 127.0.0.1 -n 30 > NUL

rem ------------------------------
rem startup tomcat
rem ------------------------------
call startup.bat

Schedule It

Simply place the command in a batch script, schedule it through Windows built-in “Scheduled Tasks” function and you have yourself an automated way to restart TOMCAT on a schedule basis.


About this entry