如何在 sh 文件 30 分钟后停止 PHP cron 作业

How to stop PHP cron job after 30 minutes from sh file

我是 运行 一个 php yii2 cron 从 cronjob 每分钟通过一个 sh 文件,所以如果之前的工作没有在一分钟内完成,那么它不会执行超过 1时间。但我的问题是,它卡住了一段时间,我必须手动终止这个过程。如果它从过去 30 分钟 运行 我怎么能杀死一个 cronjob。 目前我的 sh 文件如下所示:

if ps -ef | grep -v grep | grep cron/my-cron-action; then
        exit 0
else
        php /home/public_html/full-path-to-project/yii cron/my-cron-action
        exit 0
fi

我写了一个测试。使用check_test_demo.sh检测test_demo.sh

#test_demo.sh

#!/usr/bin/env bash
echo $(date +%s) > ~/temp_timestamp.log
echo process start
while [ 1 ]; do
    date
    sleep 1
done
#check_test_demo.sh


#!/usr/bin/env bash
process_num=$(ps -ef | grep -v grep | grep  test_demo.sh | wc -l)
if [ $process_num -gt 0 ]; then
        now_time=$(date +%s)
        start_time=$(cat ~/temp_timestamp.log)
        run_time=$((now_time - $start_time))
        if [ $run_time -gt 18 ]; then
            ps aux | grep -v grep | grep  test_demo.sh | awk '{print "kill -9 " }' | sh
            nohup ~/dev-project/wwwroot/remain/file_temp/test_demo.sh  > /dev/null 2>&1 &
            echo "restart success"
            exit
        fi
        echo running time $run_time seconds
else
        nohup ~/dev-project/wwwroot/remain/file_temp/test_demo.sh  > /dev/null 2>&1 &
        echo "start success "
fi

回答,不知道对不对。你可以试试。 我觉得你应该先记录一个进程的开始时间

#!/usr/bin/env bash
process_num=$(ps -ef | grep -v grep | grep cron/my-cron-action | wc -l)

if [ $process_num -gt 0 ]; then
        now_time=$(date +%s)
        start_time=$(cat ~/temp_timestamp.log)
        run_time=$((now_time - $start_time))
        if [ $run_time -gt 1800 ]; then
            ps aux | grep -v grep | grep  cron/my-cron-action | awk '{print "kill -9 " }' | sh
            echo $(date +%s) > ~/temp_timestamp.log
            php /home/public_html/full-path-to-project/yii cron/my-cron-action
            echo "restart success"
            exit
        fi
        echo "process running time : $run_time seconds ."
else
        echo $(date +%s) > ~/temp_timestamp.log
        php /home/public_html/full-path-to-project/yii cron/my-cron-action
        echo "process start success"
fi