Method of writing shell script to realize tomcat timing restart

My environment is centos 7

1. Create a new .sh script file in a directory (generally cron is installed in var/spool/cron, so I created the script here)

vim  /var/spool/cron/tomcatStart.sh

2. Write the code in the tomcatStart.sh file

#!/bin/bash
/etc/profile
tomcatPath="/usr/local/tomcat"
binPath="$tomcatPath/bin"
echo "[info][$(date)]正在监控tomcat,路径:$tomcatPath"
pid=`ps -ef | grep tomcat | grep -w $tomcatPath | grep -v 'grep' | awk '{print $2}'`
if [ -n "$pid" ]; then
echo "[info][$(date)]tomcat进程为:$pid"
echo "[info][$(date)]tomcat已经启动,准备使用shutdown命令关闭"
$binPath"/shutdown.sh"
sleep 2
pid=`ps -ef | grep tomcat | grep -w $tomcatPath | grep -v 'grep' | awk '{print $2}'`
if [ -n "$pid" ]; then
echo "[info][$(date)]使用shutdown关闭失败,准备kill进程"
kill -9 $pid
echo "[info][$(date)]kill进程完毕"
sleep 1
else
echo "[info][$(date)]使用shutdown关闭成功"
fi
else
echo "[info][$(date)]tomcat未启动"
fi
echo "[info][$(date)]准备启动tomcat"
$binPath"/startup.sh"

Note: if [-n "$pid" ]; then, there must be a space after the bracket "[" in this statement, and a space before "]"

3. Modify the permissions of tomcatStart.sh

 chmod +x   /var/spool/cron/tomcatStart.sh

4. Add script to crontab timing task

vi /etc/crontab

// The first is the path of tomcatStart.sh, the second is to output the log to a file

00 03 * * * root   /var/spool/cron/tomcatStart.sh >> /usr/local/tomcat/tomcatStartLog.txt

5. Restart crontab to take effect

systemctl restart crond

or

service crond restart 

Note: if [-n "$pid" ]; then, there must be a space after the bracket "[", and there must be a space before "]".
Note: The timer and other operations are not described in detail, please refer to linux timing for details Backup MySQL database

Author: 10676
Link: https: //www.jianshu.com/p/45455f36e859

Guess you like

Origin blog.csdn.net/qq_40907977/article/details/114882865