編寫shell腳本實現tomcat定時重啟


最近我在學生價買的低配服務器上部署了一個很吃內存的網頁,導致 tomcat 內存經常溢出而崩潰。
於是我上網找了一些教程編寫了一個簡單的每天定時啟動 tomcat 的腳本,特此記錄一下
我的環境是 centos 7

  • 1、 在某個目錄新建一個 .sh 腳本文件

vim tomcatStart.sh

  • 2、 在 tomcatStart.sh 文件里面寫入一下代碼
#!/bin/bash
/etc/profile
tomcatPath="/usr/local/tomcat9"
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"
  • 3、 修改 tomcatStart.sh 的權限

sudo chmod 777 tomcatStart.sh

  • 4、 添加腳本到 crontab 定時任務

crontab -e

// 第一個是 tomcatStart.sh 的路徑, 第二個是將日志輸出到某個文件中
00 03 * * * /usr/local/tomcat9/bin/tomcatStart.sh >> /home/zhang/tomcatLog.txt
  • 5、 重啟一下 crontab 以生效

systemctl restart crond

除了這種手動重啟的方法,還有優化 tomcat 的方法,這個等有時間再去探索了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM