bash - 如果进程已经运行超过一小时,则终止它

bash - 如果进程已经运行超过一小时,则终止它

我有这个 bash 脚本,它每 5 分钟在 Ubuntu 服务器中运行一次 python 程序(如果尚未运行),我想让它在运行超过一个小时后终止该程序并重新运行它。

#!/bin/bash

if pgrep -f "/home/user/crawler/panel/crawler/scans.py"
then
    echo "script running"
    # Command when the script is runnung
else
    echo "script not running"
    /home/user/crawler/env/bin/python /home/user/crawler/panel/crawler/scans.py
fi

答案1

我修改了您提供的脚本来执行您想要的操作(很快就煮熟了,但应该够用)...我尝试尽可能多地进行评论,因此请阅读下面脚本中的评论。

#!/bin/bash

if pgrep -f "/home/user/crawler/panel/crawler/scans.py"
then
    echo "script running"
    process_id=$(pgrep -f "/home/user/crawler/panel/crawler/scans.py") # Get the PID
    process_time=$(ps -p "$process_id" -o etime | awk -F":" 'NR==2 && NF>2{print 1}') # Get process elapsed time and print "1" if more than an houer
    [ "$process_time" == 1 ] && kill "$process_id" && /home/user/crawler/env/bin/python /home/user/crawler/panel/crawler/scans.py # If the process has been running for more than one hour then kill it and run the script again
    # Command when the script is runnung
else
    echo "script not running"
    /home/user/crawler/env/bin/python /home/user/crawler/panel/crawler/scans.py
fi

相关内容