Run php script as daemon process Run php script as daemon process unix unix

Run php script as daemon process


You could start your php script from the command line (i.e. bash) by using

nohup php myscript.php &

the & puts your process in the background.

Edit:
Yes, there are some drawbacks, but not possible to control? That's just wrong.
A simple kill processid will stop it. And it's still the best and simplest solution.


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:

# Infodescription "My PHP Worker"author      "Jonathan"# Eventsstart on startupstop on shutdown# Automatically respawnrespawnrespawn 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 startsudo 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.


With new systemd you can create a service.

You must create a file or a symlink in /etc/systemd/system/, eg. myphpdaemon.service and place content like this one, myphpdaemon will be the name of the service:

[Unit]Description=My PHP Daemon Service#May your script needs MySQL or other services to run, eg. MySQL MemcachedRequires=mysqld.service memcached.service After=mysqld.service memcached.service[Service]User=rootType=simpleTimeoutSec=0PIDFile=/var/run/myphpdaemon.pidExecStart=/usr/bin/php -f /srv/www/myphpdaemon.php arg1 arg2> /dev/null 2>/dev/null#ExecStop=/bin/kill -HUP $MAINPID #It's the default you can change whats happens on stop command#ExecReload=/bin/kill -HUP $MAINPIDKillMode=processRestart=on-failureRestartSec=42sStandardOutput=null #If you don't want to make toms of logs you can set it null if you sent a file or some other options it will send all php output to this one.StandardError=/var/log/myphpdaemon.log[Install]WantedBy=default.target

You will be able to start, get status, restart and stop the services using the command

systemctl <start|status|restart|stop|enable> myphpdaemon

The PHP script should have a kind of "loop" to continue running.

<?phpgc_enable();//while (!connection_aborted() || PHP_SAPI == "cli") {  //Code Logic  //sleep and usleep could be useful    if (PHP_SAPI == "cli") {        if (rand(5, 100) % 5 == 0) {            gc_collect_cycles(); //Forces collection of any existing garbage cycles        }    }}

Working example:

[Unit]Description=PHP APP Sync ServiceRequires=mysqld.service memcached.serviceAfter=mysqld.service memcached.service[Service]User=rootType=simpleTimeoutSec=0PIDFile=/var/run/php_app_sync.pidExecStart=/bin/sh -c '/usr/bin/php -f /var/www/app/private/server/cron/app_sync.php  2>&1 > /var/log/app_sync.log'KillMode=mixedRestart=on-failureRestartSec=42s[Install]WantedBy=default.target

If your PHP routine should be executed once in a cycle (like a diggest) you may should use a shell or bash script to be invoked into systemd service file instead of PHP directly, for example:

#!/usr/bin/env bashscript_path="/app/services/"while [ : ]do#    clear    php -f "$script_path"${1}".php" fixedparameter ${2}  > /dev/null 2>/dev/null    sleep 1done

If you chose these option you should change the KillMode to mixed to processes, bash(main) and PHP(child) be killed.

ExecStart=/app/phpservice/runner.sh phpfile parameter  > /dev/null 2>/dev/nullKillMode=process

This method also is effective if you're facing a memory leak.

Note: Every time that you change your "myphpdaemon.service" you must run `systemctl daemon-reload', but do worry if you not do, it will be alerted when is needed.