Saturday, January 29, 2011

Php running a script in background

Some times we want any script to be run in background which may take a longer time to complete and it should run even if the user session is over.

The nohup linux command is useful for such need. Also we can set priority to this script so that server will not get overloaded due to script.

This will execute your script scriptfile.php in background, It returns process id created by the system which you can use to monitor the process.

<?php

$PID = shell_exec(“nohup php -f scriptfile.php 1>/dev/null & echo $!”);

?>
 

If you want to run this script with a low priority, to avoid system overhead use nice keyword

<?php

$PID = shell_exec(“nohup nice php -f scriptfile.php 1>/dev/null & echo $!”);

?>
 

If you want to pass arguments to this script, the arguments will be available in scriptfile.php in array $_SERVER['argv']

<?php

PID = shell_exec(“nohup nice php -f scriptfile.php $arg1 $arg2 1>/dev/null & echo $!”);

?>
 

You can monitor process status like this

<?php

function is_running($PID){

exec(“ps $PID”, $ProcessState);

if(count($ProcessState) >= 2)

{

return ‘yes’;

}

else{

return ‘no’;

}

}

?>
 

No comments:

Post a Comment