Momen Zalabany
Momen Zalabany

Reputation: 9007

php methods to trigger async function after request end

in certain apps, you sometimes need to do processing that is irrelevant to response. for example send push notifications after chat message etc. such tasks has no effect on response you will return to user.

what is best approach to run such tasks ?

example in an API for a blog, after post is created i want to send 201 to client and end connection. yet afterwords i want to send a curl call to push notification server, or trigger some data analysis and save it to disk. yet i dont want user to wait for such tasks to end.

methods i can think of 1. is sending connect: closed and content-length headers and flush out response, but this is not compatible with all servers and not all browsers. 2. trigger task using php exec function ! ? but how can i pass a json object to that function then :/ ?

so any ideas how we can accomplish this in async behaviour for php in a manner that would works in any server setup ?

Upvotes: 1

Views: 562

Answers (2)

Khalil Kamran
Khalil Kamran

Reputation: 65

I would do it with this code: Register as many functions as required with register_shutdown_function of php:

register_shutdown_function('background_function_name_1');
register_shutdown_function('background_function_name_2');

write below lines after html end tag(if any) where all output has been printed (adjust time limit as per upper limit of script execution):

ignore_user_abort(true);
set_time_limit(120);
header('Connection: close');
header('Content-Length: ' . ob_get_length());
ob_end_flush();
flush();

Here the server will send output to browser and all the registered functions will be called in the order they were registered.

Upvotes: 1

Oleg Butuzov
Oleg Butuzov

Reputation: 5395

You can take an example of how WordPress triggering wp-cron.php functionality by sending HEAD request to wp-cron.php using curl, which is perfectly fitted to your idea of sending the request and not waiting to respond.

Upvotes: 1

Related Questions