How to perform asynchronous tasks in PHP? [duplicate]

0

I have a simple virtual store system, where the customer makes an order for certain products and the system records this, the moment the customer registers the order the system sends an email message and also communicates with an API passing the request data. The problem is that this entire process is taking a long time to run so I can give a successful response to the client. The act of sending the email and communicating with the API are not required for me to give a successful response to the client.

Having explained my situation, I wanted the system to be able to record the customer's request and immediately return the successful response, and then perform the actions of sending the email and communicating with the API.

I had two ideas, but I did not find a solution for them:

1 - The first idea would be to return the response to the client and continue with the rest of the script without my page getting stuck with these actions. It turns out that currently my php script only returns the message to the client when it finishes all the tasks (send email and API).

Ex: Customer requests -> System logs request -> System responds to client [End of communication with client] -> System sends email -> System communicates API

2 - The second alternative was to create something similar to threads, however as it is a WebAPP my Apache server does not support pthreads.

I wonder if there is a solution to this problem.

PHP code I'm using:

// Funcao registra pedido 
$resultado = registraPedido($_POST);
if ($resultado) {
  //Funcao envia e-mail 
  enviaEmail($resultado);
  //Funcao comunica API 
  comunicaAPI($resultado);
  echo 'SUCESSO';
} else {
  echo 'ERRO';
}
    
asked by anonymous 20.02.2017 / 20:04

1 answer

1

Good afternoon Marcelo,

... when the customer registers the request the system sends an email message and also communicates with an API passing the request data. The problem is that this entire process is taking a long time to run so I can give a successful response to the client.

I have also had the same problem and learned that we can not depend on external resources as an SMTP server, so I suggest you trigger these actions as background processes,

Example in GNU / Linux:

exec ("php index.php envia_email / EnviaEmailPedido index {$ pid-> idPedido} > / dev / null 2 > & 1 &");

Where the part that really matters is the end of the command > /dev/null 2>&1 &

In this way you have a process in the background (or asynchronous to your main process in Apache, the site with the graphical interface) that can take more time without worries, even in the sending of emails you can try to send N times if the first attempt fail.

    
20.02.2017 / 23:09