Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run an asynchronous PHP task using Symfony Process

For time-consuming tasks (email sending, image manipulation… you get the point), I want to run asynchronous PHP tasks.

It is quite easy on Linux, but I'm looking for a method that works on Windows too.

I want it to be simple, as it should be. No artillery, no SQL queueing, no again and again installing stuff… I just want to run a goddamn asynchronous task.

So I tried the Symfony Process Component. Problem is, running the task synchronously works fine, but when running it asynchronously it exits along the main script.

Is there a way to fix this?


composer require symfony/process

index.php

<?php
require './bootstrap.php';
$logFile = './log.txt';

file_put_contents($logFile, '');

append($logFile, 'script (A) : '.timestamp());

$process = new Process('php subscript.php');
$process->start(); // async, subscript exits prematurely…
//$process->run(); // sync, works fine

append($logFile, 'script (B) : '.timestamp());

subscript.php

<?php
require './bootstrap.php';
$logFile = './log.txt';

//ignore_user_abort(true); // doesn't solve issue…

append($logFile, 'subscript (A) : '.timestamp());
sleep(2);
append($logFile, 'subscript (B) : '.timestamp());

bootstrap.php

<?php
require './vendor/autoload.php';
class_alias('Symfony\Component\Process\Process', 'Process');

function append($file, $content) {
    file_put_contents($file, $content."\n", FILE_APPEND);
}

function timestamp() {
    list($usec, $sec) = explode(' ', microtime());
    return date('H:i:s', $sec) . ' ' . sprintf('%03d', floor($usec * 1000));
}

result

script (A) : 02:36:10 491
script (B) : 02:36:10 511
subscript (A) : 02:36:10 581
// subscript (B) is missing
like image 594
Gras Double Avatar asked Mar 24 '15 02:03

Gras Double


People also ask

Is Symfony asynchronous?

The Symfony Framework itself is synchronous as the code flow is static, starting and ending to the front controller in a logical way. You can do asynchronous programming by deferring tasks to message queues to be handled by another process.

Can Async PHP?

What Is Asynchronous PHP? Asynchronous PHP refers to PHP code that is written using the asynchronous model. In other words, asynchronous applications can multi-task. This is critical because traditionally, there's a lot of time when a CPU sits idle while a PHP application manages I/O tasks.


1 Answers

Main script must be waiting when async process will be completed. Try this code:

$process = new Process('php subscript.php');
$process->start();
do {
    $process->checkTimeout();
} while ($process->isRunning() && (sleep(1) !== false));
if (!$process->isSuccessful()) {
   throw new \Exception($process->getErrorOutput());
}
like image 76
Mikhail Avatar answered Sep 18 '22 20:09

Mikhail