3

I'm writing a Wordpress plugin that runs a PHP script on initiation and listens for events continuously using WebSockets and logs connections.

e.g.

shell_exec('php restserver.php >restserver.log 2>&1 &');

The script mentioned is outside of the Wordpress API. Im aware using exec or shell_exec is an extreme method (often the answer to a worng question).

I have managed to record the restserver.php process ID to be able to kill it if the plugin is disabled and to not re-launch the script if the plugin is reinitiated.

So in short...

  1. Is there a better way to run a background php process that is independant of wordpress?
  2. Is there a "best practice" way to detect the plugin disable event and launch the kill process command before this?

EDIT: The secret to question number 2, apparently lies in using register_deactivation_hook() after register_activation_hook(), to register your class or functions that make the magic.

It worked for me anyway. Any further information about using exec() the right way is always welcome.

H.Muster
  • 9,187
  • 1
  • 31
  • 45

1 Answers1

0

There is a unix server called GearMan which was designed for parallel execution of various tasks. It has a client library for PHP which allows you to launch the workers and monitor their execution, including background jobs. So this would be one (elegant) way to do it but it requires installing the GearMan server and the client library which means administrative access.

Another simple way to do it is to add a cronjob for this. This only requires access to write to the cronjob file and to ask the cronjob daemon to load the new settings. Launching PHP from a cronjob for your tasks purpose makes more sense than launching it from an exec call.

Community
  • 1
  • 1
Mihai Stancu
  • 14,701
  • 2
  • 30
  • 49
  • Thank you, I think I'll go with the cronjob, since I can make it start immediately and remove it when the plugin un-installs. – Patxi Pierce Sep 04 '12 at 16:46