Linux 定时重启 Tomcat、重启Keepalived


1、在 tomcat 目录新建一个.sh 文件:

vi restartTomcat.sh

2、输入内容:

#!/bin/bash
# author: Linnuo # date:
2019-05-31 # Filename: restartTomcat.sh # Description: 重启tomcat服务 # 声明环境变量,可重复使用 export LANG=zh_CN.UTF-8 export JAVA_HOME=/usr/java/jdk1.8.0_161 export JRE_HOME=${JAVA_HOME}/jre export TOMCAT_HOME=/tomcat/apache-tomcat-9.0.17/ # 输出开始时间 echo "[$(date +'%F %T')] >>> Tomcat begin to restart." # 关闭tomcat服务 ${TOMCAT_HOME}/bin/shutdown.sh # Kill all remaining processes 杀掉所有残留进程,不杀掉会占用系统资源 pidList=$(ps aux | grep ${TOMCAT_HOME} | grep -v grep | awk '{print $2}') if [ "${pidList}" != "" ] then echo "残留的进程号:${pidList}"; for pid in $pidList; do kill -9 $pid echo "[$(date +'%F %T')] >>> Kill the process [$pid] successfully." done else echo "无 残留的进程号"; fi # 启动tomcat服务 ${TOMCAT_HOME}/bin/startup.sh # 获取重新启动后的tomcat服务的进程号 pidList2=$(ps aux | grep ${TOMCAT_HOME} | grep -v grep | awk '{print $2}') if [ "${pidList2}" != "" ] then echo "启动后的进程号:${pidList2}"; echo "[$(date +'%F %T')] >>> Tomcat restart complete." echo -e "本次tomcat成功重启 \n\n" else echo "本次tomcat服务启动出错,请查看/logs/catalina.out日志文件" fi # 重启keepalived服务 systemctl restart keepalived # 查看状态 service keepalived status

  JAVA_HOME、TOMCAT_HOMT 根据自己路径输入,保存。

3、给.sh 文件赋予执行权限:

chmod +x restartTomcat.sh

4、运行:

./restartTomcat.sh

 5、配置定时任务 crond:

vi /etc/crontab

6、最下面添加红色内容:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

25 0 */2 * *  root /root/restartTomcat.sh >> /root/restartLog.txt

# 每两天的 00:25 执行一次 - 用户 - 执行的脚本路径 - 执行信息的输出位置 - 执行信息存放的文件名


保存退出后,系统自动读取加载,间隔到点,会看见 root 目录下多了个存放执行信息的文件 restartLog.txt

至此,Linux 中 Tomcat\Keepalived 定时重启的功能完成.

TIPS:
  1、如果定时任务未生效,重启即可
  2、如果定时任务只执行shutdown、未执行start,将shutdown、start分开写即可
service crond restart