#!/bin/bash

服务进程定时检测脚本,配合 crontab 使用,每分钟执行一次

#* * * * * sh /....../service.sh

按需修改进程数组(processArray),以及进程检测时间间隔(interval)

进程数组

key 为进程标识,保证通过 ps -ef | grep 'key' | grep -v grep 可获取到唯一进程,兼容正则表达式,不可包含空格

value 为启动命令

processArray=( ['STLservice']='cd /home/tumispider/tumispider/stl2023 && nohup python3 main.py --tries=3 --backoff=10 > /var/log/STLservice.log 2>&1 &' )

进程检测时间间隔,单位秒

interval=2

脚本执行开始时间戳

startTimeStamp=$(date +%s)

检测脚本执行时间,如果超过 59 秒,则退出脚本,参数为脚本执行开始时间戳

function timeCheck() { currTimeStamp=$(date +%s) exeTime=expr $currTimeStamp - $1 echo "execute time: $exeTime second" if [ $exeTime -ge 59 ]; then echo "done" exit 0 fi }

检测进程是否存在,不存在则启动,第一个参数为进程标识,第二个参数为启动命令

function checkProcess() { timeCheck $startTimeStamp

ps -ef | grep -E '$1' | grep -v grep
if [ $? -ne 0 ]; then
    echo "start $1 process"
    eval $2
    echo -e "\n"
else
    echo -e "$1 process is runing\n"
fi

sleep $interval

}

开始循环检测

while true do for key in ${!processArray[@]} do checkProcess '$key' "${processArray[$key]}" done done

Bash 脚本:服务进程定时检测脚本,配合 crontab 使用

原文地址: https://www.cveoy.top/t/topic/oWt5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录