How to Restart Tomcat via Shell Script Using Cron

By | February 2, 2010

Sometimes we need to automatically restart Tomcat server. Here is the way to do that automatically, using a shell script and our crontab.

First of all, we will add some variables to our /etc/crontab file.

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/java/jdk1.5.0_07/bin
MAILTO=root
HOME=/home/admin/
JAVA_HOME=/usr/java/jdk1.5.0_07/bin/java

You should change these paths (/usr/java/jdk1.5.0_07/bin and /usr/java/jdk1.5.0_07/bin/java) if they are different for your system. These paths and variables will be used by our shell script, that will restart Tomcat.

#!/bin/bash
export JAVA_HOME=/usr/java/jdk1.5.0_07/bin/java
export PATH=$PATH:/usr/java/jdk1.5.0_07/bin
if [ `netstat -nlp | grep :3128 | wc -l` = 1 ]; then
{
echo live
kill -9 `ps -ef|grep java|awk ‘{print $2}’`
}
fi
sleep 5
cd /usr/local/apache-tomcat-6.0.13/
sh ./bin/startup.sh > err.txt

Please, ensure that the location of startup.sh is the same or check the path to it if necessary.