【问题标题】:How to stop PHP cron job after 30 minutes from sh file如何在 sh 文件 30 分钟后停止 PHP cron 作业
【发布时间】:2021-09-18 16:58:56
【问题描述】:

我每分钟通过一个 sh 文件从 cronjob 运行一个 php yii2 cron,所以如果前一个作业在一分钟内没有完成,那么它不会执行超过 1 次。但我的问题是,它卡住了一段时间,我必须手动终止这个过程。如果 cronjob 从过去 30 分钟开始运行,我怎么能杀死它。 目前我的 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

【问题讨论】:

  • 一个快速的想法是,您可以将 PID 文件放在某个地方(例如 /var/run),然后让您的文件检查其上的创建时间戳并杀死任何超过 30 分钟的内容。

标签: php yii cron sh


【解决方案1】:

我写了一个测试。使用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 " $2}' | 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 " $2}' | 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


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-30
    • 2015-07-15
    • 2022-12-18
    • 2018-05-02
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    相关资源
    最近更新 更多