2

I have a webpage, which will be creating a buch of multithreaded calls before page contents are returned to the end user. The content of this php page are NOT dependent on the threads that it creates . The content of the page can (and most likely will) finish before the threads are finished

Here is a pseudo code

<?php

    // Step 1: Start php multithreading
    // CODE HERE (will probably take 20 seconds to finish)

    // Step 2: Do other stuff and return the php page, mostly static things using html
    // CODE HERE (will probably take 1 second to return)
?>

Now, if you look closely, the web page will still be "loading" until the code of step 1 above is finished (i.e., the page will show a rotating icon on the web browser until it is completely finished), which is about 20 seconds.

Moreover, if the webpage is closed, the script in step 1 is terminated halfway.

Now, I would like to do the following:

How to make the thread of step 1 independent of the page? i.e, if the page is closed, the thread keeps running.

Also, since the thread of step 1 is independent of the page, I want the page to finish loading once the content of step 2 are done, without waiting for step 1 to finish.

Thanks.


Update

I am thinking this might be possible via a php script invoking another php script, but not sure how.

Greeso
  • 7,544
  • 9
  • 51
  • 77
  • Possible duplicate of [How can I run a PHP script in the background after a form is submitted?](http://stackoverflow.com/questions/4626860/how-can-i-run-a-php-script-in-the-background-after-a-form-is-submitted) – Ken Y-N Dec 22 '15 at 03:08
  • 1
    Maybe a queue could help. Then the webpage simply checks the status of the item in the queue. – Aerendir Dec 22 '15 at 03:21
  • can you please tell us what you want to achieve in step 1 ? so that we can suggest accordingly – razahassank Dec 22 '15 at 04:29
  • try putting `ini_set('memory_limit', '-1');` `ini_set('max_execution_time', 300000000);` in ur php code and try what u r trying to do. it worked in my project – dhpratik Dec 22 '15 at 08:53
  • I think you can get your answer with this [link](http://stackoverflow.com/questions/4626860/how-can-i-run-a-php-script-in-the-background-after-a-form-is-submitted) – Monty Dec 22 '15 at 09:58

2 Answers2

0

Have a look at fastcgi_finish_request. With this function you can return page content to user, but continue to execute your script on server.

hypnoglow
  • 1,483
  • 14
  • 16
0

I don't think you are approaching the right way. Probably with the long running and heavy task you should use a work queue to process them and send back to the user when it's finished. The work flow should be like this: Request -> create job and put them into queue -> check status of item in queue -> when it's done -> show response to the user. There are a lot of solution out there to achieve this architecture. Please take a look at this: http://queues.io

trongd
  • 273
  • 2
  • 9