PHP how to have code continue without waiting for

2019-06-01 06:55发布

I'm hoping there is a simple solution here:

My code is basically

....some code.... //populates a MySQL table

include 'run_this_page.php'; //uses data from table above and takes ten minutes to run

....lots more code.... ///also uses data from same table

As the include takes ten minutes to excute, I'd like for it to be initiated and then move on immediately to the next step. Nothing in the include is required for these next steps. I can think of several non-elegant (create a txt file which will trigger a scheduled task in Windows rather than using include etc) ways to achieve this, is there a more elegant method?

*Update*

I'm being attacked (politely) by many over the structure of my script. Let me explain a bit more what the purpose is:

1 - Raw data is gathered from a 3rd party API, filtered via the script and stored in the database. Because of limitations in this API, I have to restrict the requests to small chunks and this can easily take over 20 minutes. From this data I am looking for two distinct result sets. Each one of these sets are stored in its own table. This will soon grow to a dozen result sets in a dozen tables. (I could use only one table, but it makes no difference for our discussion).

2 - Now that I have the result sets, I have two distinct scripts that go out and gather data about each. Because the target 3rd party sites are completely different I wrote the scripts in their own files and simply want them to both run now. Each can take upwards of ten minutes.

I hope this explanation helps

标签: php include
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-01 07:22

Open a socket, write to it and close the socket. Be careful, your code will be executing asynchronously:

$sock = fsockopen($url,$port);
$packet = "POST $path?$get HTTP/1.1\r\n";
$packet.= "Host: $host\r\n";
$packet.= "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n";
$packet.= "Connection: Close\r\n\r\n";
$packet.= $post;
fwrite($sock, $packet);
fclose($sock);
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-06-01 07:32

A simple method to load PHP asynchronously is to just use jQuery and AJAX.

<? // php code you want to run 1st ?>
<div id="content"></div>
<script>
$( "#content" ).load( "example.php" ); // php to run 3rd
</script>
<? // php code you want to run 2nd ?>

OR ...

A more robust solution, if you want to load example.php on demand, would be to run a cron job programmatically when the user clicks a 'process data' button on that page.

Then you could use AJAX to ping the server every 60 seconds until the data is updated and pull it in using the same code from above.

OR ...

php execute a background process

查看更多
登录 后发表回答