Wednesday, August 8, 2012

Triggering an Asynchronous Process from PHP, Without Waiting to Complete

Triggering an Asynchronous Process from PHP, Without Waiting to Complete

Sometimes, we need to send a large amount of emails, sms or pushnotification from current script & the current page waits until al the stuffs are done.

To, overcome this thing, we can simply trigger a new process asynchronously and pass parameters to it, without making any wait conditions. The process will start and take its time to complete, without affecting the parent script.

we can use exec() or system() function for that. The difference is System() also prints the output.
Structure- exec('PATH/TO/PHP PATH/TO/FILE.PHP');

1. Here is a sample command to call another script from current file as a separate process-

exec('/usr/bin/php5 /var/www/vhosts/');

2. Doing the above will start the script as a new process, but the parent script will still wait - this process to complete. To overcome that we will modify our command to this-

exec('/usr/bin/php5   /var/www/vhosts/ > /dev/null 2>&1 &');

3. Now, the process will execute, without keeping the parent to wait. But, we surely need to pass parameters to the process Script. That will be simply accomplished using $argv. $argv returns an array of arguments passed to script.

In this example, we will pass a parameter: 15 to the processScript.php-

exec('/usr/bin/php5   /var/www/vhosts/  15 > /dev/null 2>&1 &');

- we are done.
- In processScript.php, we will get the parameter: 15 by-

$paramID = $argv[1];  //$argv[0] is always the name that was used to run the script

- and that's all- we need to run a new PHP process. Please post a comment if you have any query or if you like the post.