How to check if a php script is still running

前端 未结 13 2456
鱼传尺愫
鱼传尺愫 2020-12-15 12:02

I have a PHP script that listens on a queue. Theoretically, it\'s never supposed to die. Is there something to check if it\'s still running? Something like

相关标签:
13条回答
  • 2020-12-15 12:38

    Not for windows, but...

    I've got a couple of long-running PHP scripts, that have a shell script wrapping it. You can optionally return a value from the script that will be checked in the shell-script to exit, restart immediately, or sleep for a few seconds -and then restart.

    Here's a simple one that just keeps running the PHP script till it's manually stopped.

    #!/bin/bash
    clear
    date
    php -f cli-SCRIPT.php
    echo "wait a little while ..."; sleep 10
    exec $0

    The "exec $0" restarts the script, without creating a sub-process that will have to unravel later (and take up resources in the meantime). This bash script wraps a mail-sender, so it's not a problem if it exits and pauses for a moment.

    0 讨论(0)
  • 2020-12-15 12:39

    Simple bash script

    #!/bin/bash
    while [true]; do
        if ! pidof -x script.php;
        then
            php script.php &
        fi
    done
    
    0 讨论(0)
  • 2020-12-15 12:40

    Here is what I did to combat a similar issue. This helps in the event anyone else has a parameterized php script that you want cron to execute frequently, but only want one execution to run at any time. Add this to the top of your php script, or create a common method.

    $runningScripts = shell_exec('ps -ef |grep '.strtolower($parameter).' |grep '.dirname(__FILE__).' |grep '.basename(__FILE__).' |grep -v grep |wc -l');
    if($runningScripts > 1){
        die();
    }
    
    0 讨论(0)
  • 2020-12-15 12:43

    Just append a second command after the script. When/if it stops, the second command is invoked. Eg.:

    php daemon.php 2>&1 | mail -s "Daemon stopped" you@example.org
    

    Edit:

    Technically, this invokes the mailer right away, but only completes the command when the php script ends. Doing this captures the output of the php-script and includes in the mail body, which can be useful for debugging what caused the script to halt.

    0 讨论(0)
  • 2020-12-15 12:43

    If you have your hands on the script, you can just ask him to set a time value every X times in db, and then let a cron job check if that value is up to date.

    0 讨论(0)
  • 2020-12-15 12:48

    If you're having trouble checking for the PHP script directly, you can make a trivial wrapper and check for that. I'm not sufficiently familiar with Windows scripting to put how it's done here, but in Bash, it'd look like...

    wrapper_for_test_php.sh

    #!/bin/bash
    php test.php
    

    Then you'd just check for the wrapper like you'd check for any other bash script: pidof -x wrapper_for_test_php.sh

    0 讨论(0)
提交回复
热议问题