Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Running Background jobs without waiting for response Non Blocking mode Like Trigger type

Objective

My basic objective is to acheive asynchornous triggers in PHP using Yii2 Web Application

I need to run the php batch jobs but i dont want to wait in the browser / cron for doing the job. For running the job i need to use different file of my application like

http://myapp/foojob.php 

The foojob.php should be asynchronously call many php instances[Each instance carries one job] based on the availble jobs in hand. The time limit of the call (foojob.php) is less than 60sec.i need to trigger new php instances before it exceeds timeout value.

I Referred & Tried

  1. curl_multi - i could't find the non blocking mode in it .
  2. fsock_open - This is possible by sending Connection: Close to the call (But fsock open is not always available on many shared hosting servers or its not working properly) . Can you suggest me any Reliable solution with the fsock transport?
  3. pcntl_exec -I haven't tried in real time but realtime stats shows 45% servers disabled the function. I dont know the reason why.
  4. stream transport - I dont know how it works?

My Questions :

  1. Non blocking async requests Is there any possible solution that already exists in git to acheive in PHP?
  2. Refer me if any other transports i need to look into
  3. is there any smart switching transport mechanism (curl/ fsock) based on the environment ?

Edit:

The application is self-hosted product . it would get work on Various hosting services . Shared Hosting won't allow / Provide any external extensions for their customer .

like image 461
Babu Avatar asked Oct 18 '16 12:10

Babu


1 Answers

You could take an approach where you send the correct headers to have the browser close the connection and then run the process synchronously and it would appear to be async to the end user.

Here is something I wrote a long time ago that you can see as an example. http://www.phpclasses.org/package/8388-PHP-Defer-execution-of-actions-until-the-script-ends.html

I assume there is some place in yii that you could hook into after the content is sent where you could do a similar thing.

Short version of it header("Content-Length: ".$length); header("Connection: Close");

ob_flush(); // headers
echo $html;
flush();

doWork();
like image 83
matthewdaniel Avatar answered Oct 23 '22 18:10

matthewdaniel