Start processes in the background that continue running when the PHP process exists.
You can install cocur/background-process using Composer:
$ composer require cocur/background-process:@stable
In a production environment you should replace @stable
with the version you want to use.
The following example will execute the command sleep 5
in the background. Thus, if you run the following script either in the browser or in the command line it will instantley finish executing.
use Cocur\BackgroundProcess\BackgroundProcess;
$process = new BackgroundProcess('sleep 5');
$process->run();
You can retrieve the process ID (PID) of the process and check if it's running:
use Cocur\BackgroundProcess\BackgroundProcess;
$process = new BackgroundProcess('sleep 5');
$process->run();
echo sprintf('Crunching numbers in process %d', $process->getPid());
while ($process->isRunning()) {
echo '.';
sleep(1);
}
echo "\nDone.\n";
If the process runs you can stop it:
// ...
if ($process->isRunning()) {
$process->stop();
}
Please note: If the parent process continues to run while the child process(es) run(s) in the background you should use a more robust solution, for example, the Symfony Process component.
- Moved repository to Cocur organization
- Changed namespace to
Cocur
- PSR-4 compatible namespace
- #3 Added
BackgroundProcess::stop()
(by florianeckerstorfer)
- Changed namespace to
Braincrafted
The MIT license applies to cocur/background-process. For the full copyright and license information, please view the LICENSE file distributed with this source code.