Search code examples
phpyiicronsh

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


I'm running a php yii2 cron from cronjob through a sh file every minute, so if previous job doesn't complete within a minute so it won't execute more than 1 time. But my problem is that, it got stuck some time and i have to manually kill this process. How can i kill a cronjob if it running from past 30 minutes. Currently my sh file is like below:

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

Solution

  • I write a test . Use check_test_demo.sh to detect 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
    

    answer, I don't know if it's right. You can try. I think you should record the start time of a process first

    #!/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