1. 程式人生 > 其它 >定時任務檢查埠掛了就重啟服務:

定時任務檢查埠掛了就重啟服務:

vim /root/check_port.sh
#!/bin/sh
now=`date +"%Y-%m-%d %H:%M:%S"`
export PATH="/root/bin:/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/usr/local/python3/bin:/opt/node-v14.18.2-linux-x64/bin:/usr/local/go/bin:/root/go/bin:/root/bin"
#ID=`ps -ef | grep "node" | grep -v "grep" | awk '{print $2}'`
echo "${now} 開始檢測埠>>> >>>" >> /root/astro.log
echo " " >> /root/astro.log
check_port() {
        #echo "${now} 開始檢測埠..." >> /root/astro.log
        netstat -tlpn | grep "\b$1\b" >> /root/astro.log
}
if check_port 9528
then
        sleep 3s
        DATE_N=`date "+%Y-%m-%d %H:%M:%S"`
        echo "${DATE_N} 9528埠存在,前端服務正常!ʔ•̫͡•ʕ ʕ•͡•ʔ" >> /root/astro.log
        echo " " >> /root/astro.log
else
        sleep 3s
        DATE_X=`date "+%Y-%m-%d %H:%M:%S"`
        echo "${DATE_X} 9528埠不存在,前端服務掛了...//(ㄒoㄒ)//" >> /root/astro.log
        echo "${DATE_X} 開始執行前端啟動操作..." >> /root/astro.log
        #time=`date +"%Y-%m-%d"`

        #kill -9 $ID
        #DATE_Y=`date "+%Y-%m-%d %H:%M:%S"`
        #echo "${DATE_Y} 幹掉node程序:${ID}" >> /root/astro.log
        echo "等待20秒"
        nohup /usr/local/bin/npm -prefix /root/astro/front/ run prod > /dev/null 2>&1 &
        sleep 20s

        DATE_Y=`date "+%Y-%m-%d %H:%M:%S"`
        echo "${DATE_Y} 前端服務啟動完畢!٩(͡๏̯͡๏)۶  " >> /root/astro.log
        echo " " >> /root/astro.log
fi

if check_port 8999
then
        sleep 3s
        DATE_Z=`date "+%Y-%m-%d %H:%M:%S"`    
        echo "${DATE_Z} 8999埠存在,後端服務正常!ʔ•̫͡•ʕ ʕ•͡•ʔ" >> /root/astro.log
        echo " " >> /root/astro.log
else
        sleep 3s
        DATE_M=`date "+%Y-%m-%d %H:%M:%S"`
        echo "${DATE_M} 8999埠不存在,後端服務掛了...//(ㄒoㄒ)//" >> /root/astro.log
        echo "${DATE_M} 開始執行後端啟動操作..." >> /root/astro.log
        #time=`date +"%Y-%m-%d"`
        #kill -9 $ID
        echo "等待15秒"
        nohup python3 /root/astro/main.py > /dev/null 2>&1 &
        sleep 15s

        DATE_W=`date "+%Y-%m-%d %H:%M:%S"`
        echo "${DATE_W} 後端服務啟動完畢!٩(͡๏̯͡๏)۶  " >> /root/astro.log
        echo " " >> /root/astro.log
fi
[root@VM-0-17-centos ~]# crontab -l
*/10 * * * * echo 1 > /proc/sys/vm/drop_caches
*/5 * * * * /bin/bash /root/check_port.sh > /dev/null 2>&1

效果如下: