Skip to content

Linux 下使用 crontab 自动断电重启 java 程序

方式一、单 restart.sh 脚本

bash
#!/bin/sh
APP_HOME=/app
APP_NAME=sample-quickboot-mybatis-plus-1.0.46-SNAPSHOT.jar
JVM_OPTS="-Dname=$APP_NAME -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m"

procnum=`ps -ef|grep $APP_NAME|grep -v grep|wc -l`
if [ $procnum -eq 0 ]
then
    cd $APP_HOME
    source /etc/profile
    mkdir -p logs
    echo `date +%Y-%m-%d` `date +%H:%M:%S` "restart $APP_NAME" >>$APP_HOME/logs/restart.log
    nohup java $JVM_OPTS -jar $APP_NAME > /dev/null 2>&1 &
fi

添加执行权限

bash
chmod +x restart.sh

将 restart.sh 脚本加入 crontab

bash
#进入crontab
crontab -e

#填写一下内容(中间的 /bin/bash 可以改为 /bin/sh,也可以直接省略掉。)
#开机自启动任务(未验证)
# @reboot /bin/bash /app/restart.sh
#每5分钟执行一次
*/5 * * * * /bin/bash /app/restart.sh

#每分钟执行一次
# * * * * * /bin/sh /app/restart.sh

# 查看 cron 执行日志
tail -f /var/log/cron
bash
# crontab 语法
more /etc/crontab

* * * * * command(s)
^ ^ ^ ^ ^
| | | | |     allowed values
| | | | |     -------
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

方式二、monitor.sh 调用 quickboot.sh

注意:脚本中 “source /etc/profile” 是因为 crontab 执行脚本无法取到环境变量,导致进程启动不起来,所以这个必须加上。

quickboot.sh 和 monitor.sh 以及应用 jar 存放于 /app 目录下

假如启动 java 的脚本为 quickboot.sh

bash
#!/bin/sh
APP_HOME=/app
APP_NAME=sample-quickboot-mybatis-plus-1.0.46-SNAPSHOT.jar
JVM_OPTS="-Dname=$APP_NAME -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m"

cd $APP_HOME
source /etc/profile
kill -9 `ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}'`
nohup java $JVM_OPTS -jar $APP_NAME > /dev/null 2>&1 &
echo "Start $APP_NAME success..."

监控 shell 脚本:monitor.sh

bash
#!/bin/sh
APP_HOME=/app
APP_NAME=sample-quickboot-mybatis-plus-1.0.46-SNAPSHOT.jar

procnum=`ps -ef|grep $APP_NAME|grep -v grep|wc -l`
if [ $procnum -eq 0 ]
then
    cd $APP_HOME
    source /etc/profile
    mkdir -p logs
    echo `date +%Y-%m-%d` `date +%H:%M:%S` "restart $APP_NAME" >>$APP_HOME/logs/restart.log
    # 如果启动脚本有参数,同理,此处加上即可
    ./quickboot.sh
fi

添加执行权限

bash
chmod +x quickboot.sh monitor.sh

将 monitor.sh 脚本加入 crontab

bash
crontab -e
*/5 * * * * /bin/bash /app/monitor.sh