Skip to content

Instantly share code, notes, and snippets.

@benedict-erwin
Last active July 2, 2019 17:00
Show Gist options
  • Save benedict-erwin/7f6ce8d0ae90dac7ad55067f52bb7761 to your computer and use it in GitHub Desktop.
Save benedict-erwin/7f6ce8d0ae90dac7ad55067f52bb7761 to your computer and use it in GitHub Desktop.
Run php script as daemon in linux (ubuntu) with Upstart

Run PHP Script as Daemon in Linux (ubuntu) with Upstart

How to set it up:

Create a config file for your phpdaemon at /etc/init/phpdaemon.conf

# Info
description "PHP Daemon"
author      "Benedict E. Pranata"

# Events
start on startup
stop on shutdown

# Automatically respawn
# respawn the job up to 10 times within a 5 second period.
respawn
respawn limit 10 5

# Check before running
# exit if php script already running
pre-start script
  if ps -ef | grep -v grep | grep phpdaemon; then
    stop; exit 0
  fi
end script

# 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/phpdaemon.php) = 'ERROR' ] && ( stop; exit 1; )
end script

Starting & stopping your daemon:

sudo service phpdaemon start
sudo service phpdaemon stop

Check if your daemon is running:

sudo service myphpworker status

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment