Background processes
Background
- In many cases, it might meet some needs to execute programs in the background, for example, continuous executions, high time complexity calculations, etc. But, PHP is the kinds of preprocesser for the webpage, how to deal with the problem? The following is the example showing how to implement codes with front and background codes in PHP script.
background code
- The example used sleep to simulate increasing time for executing the program. After, use a simple print() to output the result. The file name is "background_process.php".
<?php
sleep(60);
print("Execution is completed.\n");
?>
front code
- The simple code implemented how to mirror the background process with auto meta redirect in a fixed time peroid. The file name is "front_check.php".
<?php
echo 'Start to mirror the background process';
function isRunning($pid) {
try {
$result = shell_exec(sprintf("ps %d",$pid));
if(count(preg_split("/\n/",$result)) > 2) {
return true;
}
} catch (Exception $e) {
echo '[Status] exception occured.';
}
return false;
}
if($_GET["call"] == 1) {
$getStatus = isRunning($_GET["pid"]);
switch($getStatus) {
case true:
echo 'Current status: Running.';
echo '<meta http-equiv="refresh" content="1;url=/php/front_check.php?pid='.$_GET["pid"].'&call=1"></meta>';
break;
case false:
echo 'Current status: Complete.';
break;
}
} else {
$cmd = "php /var/www/html/php/background_process.php";
$outputfile = "/var/www/html/php/output.txt";
$pidfile = shell_exec(sprintf("%s > %s 2>&1 & echo $!",$cmd,$outputfile));
echo '<meta http-equiv="refresh" content="1;url=/php/front_check.php?pid='.$pidfile.'&call=1"></meta>';
}
?>
How to use them
- Use the urls to quickly implement them.
http: