Ubuntu tomcat8定时重启
由于个人使用的服务器内存等都比较小,tomcat启动几天时间内存后占用过高会被系统杀死,内存问题原因暂时未知,所以在每天凌晨自动重启一下tomcat以保证服务正常访问。
(以下操作都在root用户下进行)
创建shell脚本
在/root/下创建一个shell脚本 tcRestart.sh来自动启停tomcat。注意此shell文件名和内容中ps命令忽略项(grep -v)名称一致,否则会检测到脚本自身导致混淆。
注意:
- 其中/etc/init.d/tomcat8 stop(start) 是Ubuntu下的脚本命令,可根据自身情况替换为相应的启动停止命令
- 内容中第二行 /etc/profile 的访问权限,直接
chmod 777 /etc
和chmod 777 /etc/profile
#!/bin/sh
/etc/profile
pid=`ps aux | grep tomcat | grep -v grep | grep -v tcRestart | awk '{print $2}'`
echo $pid
if [ -n "$pid" ]
then
{
echo ===========shutdown================
/etc/init.d/tomcat8 stop
sleep 1
pid=`ps aux | grep tomcat | grep -v grep | grep -v tcRestart | awk '{print $2}'`
echo tomcatPid: $pid
if [ -n "$pid" ]
then
{
sleep 1
echo ========kill tomcat==============
kill -9 $pid
}
fi
sleep 1
echo ===========startup.sh==============
/etc/init.d/tomcat8 start
}
else
echo ===========startup.sh==============
/etc/init.d/tomcat8 start
fi
可能的错误:
java.net.ConnectException: Connection refused: connect
,参考:https://blog.youkuaiyun.com/jiangyu1013/article/details/80926682java.io.FileNotFoundException: /usr/share/tomcat6/conf/server.xml (No such file or directory)
,参考:https://blog.youkuaiyun.com/neonlight/article/details/5975768- shell脚本头,#!/bin/sh与#!/bin/bash的区别. 参考:https://www.cnblogs.com/jonnyan/p/8798364.html
创建定时任务
- 使用命令
crontab -e
,在文件尾添加30 04 * * * /root/tcRestart.sh
,注意这个命令中的时间格式,每段用空格隔开,否则退出时保存会报错:errors in crontab file, can't install.
。 - 启动定时任务,
service cron start
对应停止命令:service cron stop
,重载命令:service cron reload
- 查看日志,/var/log/cron
crontab时间格式:
格式:* * * * * command
对应:M H D m d command
对应:分 时 日 月 周 命令
第1列表示分钟1~59 每分钟用*或者 */1表示
第2列表示小时1~23(0表示0点)
第3列表示日期1~31
第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)
第6列要运行的命令或脚本内容
时间格式参考:https://blog.youkuaiyun.com/home_zhang/article/details/7996809
错误:Redirecting to /bin/systemctl start cron.service Failed to start cron.service: Unit not found.
将命令service cron start
换成 systemctl enable crond