总共两步:一,编写脚本;二,配置定时任务
1.编写shell脚本
脚本命名为restart.sh
#!/bin/sh
#初始化全局环境变量
. /etc/profile
#查找tomcat的pid
pid=`ps aux | grep tomcat | grep -v grep | grep -v Restart | grep -v restart | awk '{print $2}'`
echo "the tomcat pid is $pid"
#判断tomcat进程是否存在
if [ -n "$pid" ];then
sleep 1
pid=`ps aux | grep tomcat | grep -v grep | grep -v restart | grep -v Restart | awk '{print $2}'`
if [ -n "$pid" ]; then
sleep 1
echo "tomcat进程将被杀死."
kill -9 $pid
fi
sleep 1
echo "tomcat进程已经被杀死,先重新启动tomcat."
/opt/tomcat/bin/startup.sh
else
echo "tomcat进程不存在,先重新启动tomcat."
/opt/tomcat/bin/startup.sh
fi
注意:为避免linux下与windows下格式冲突,最好是在linux下使用vi命令创建并保存
2.配置脚本定时执行
1)crontab -e
默认进入vi编辑模式
录入 :
#设定每天X点整重启tomcat
10 9 * * * sh /opt/tomcat/restart.sh >> /opt/tomcat/restart.log
2)执行:wq , 进行保存
3)执行service crond restart,重启crontab服务
完成以上操作,即可实现tomcat的定时启动任务。