Run php script as daemon process

后端 未结 14 1589
-上瘾入骨i
-上瘾入骨i 2020-11-22 11:36

I need to run a php script as daemon process (wait for instructions and do stuff). cron job will not do it for me because actions need to be taken as soon as instruction arr

14条回答
  •  迷失自我
    2020-11-22 12:29

    Another option is to use Upstart. It was originally developed for Ubuntu (and comes packaged with it by default), but is intended to be suitable for all Linux distros.

    This approach is similar to Supervisord and daemontools, in that it automatically starts the daemon on system boot and respawns on script completion.

    How to set it up:

    Create a new script file at /etc/init/myphpworker.conf. Here is an example:

    # Info
    description "My PHP Worker"
    author      "Jonathan"
    
    # Events
    start on startup
    stop on shutdown
    
    # Automatically respawn
    respawn
    respawn limit 20 5
    
    # Run the script!
    # Note, in this example, if your PHP script returns
    # the string "ERROR", the daemon will stop itself.
    script
        [ $(exec /usr/bin/php -f /path/to/your/script.php) = 'ERROR' ] && ( stop; exit 1; )
    end script
    

    Starting & stopping your daemon:

    sudo service myphpworker start
    sudo service myphpworker stop
    

    Check if your daemon is running:

    sudo service myphpworker status
    

    Thanks

    A big thanks to Kevin van Zonneveld, where I learned this technique from.

提交回复
热议问题