[英]In PHP, how to stop function, wait, and recursively restart itself until some condition is met?
如果滿足某些條件,我該如何做函數:
會是這樣嗎?
function someFunc() {
if (x == 0) {
sleep(60);
someFunc();
return;
}
...other code only to be run if above is false...
}
someFunc();
...other code only to be run if above function finishes running completely...
如果它是相關的,並且有一些庫可以處理APi限制之類的東西,那么我將針對API連接執行此操作。 首先,我通過
file_get_contents('php://input')
其中包含一個URL。 然后我用
file_get_contents( $url )
然后將$http_response_header
解析$http_response_header
$headers
數組后,檢查它的標頭, if ($header['api_limit'] == 0) ...
(在上面的示例中為x
)。 如果"x"
為0,那么我希望函數等待一分鍾,直到限制周期重置,然后運行第二個file_get_contents( $url )
並再次進行解析。
我想用這種方式處理的主要原因是不必記錄任何東西。 我通過file_get_contents('php://input')
收到的Webhook只發生一次。 如果達到API速率限制,並且我嘗試在Webhook中使用URL,但失敗了,則該URL丟失。 因此,我希望該函數僅等待X次,直到rte重置,然后再次嘗試將webhook接收的URL與file_get_contents($url)
一起使用。 這是一種不好的做法嗎?
對於速率受限的資源,您通常希望緩存X分鍾塊的數據副本,以使該限制從未真正超出。 例如,對於每小時最多10個請求的情況,您將在嘗試獲取新響應之前將響應緩存至少6分鍾。
在提高速率限制之前,不建議暫停整個PHP解釋器。
對於一般來說,“重復嘗試直到成功為止”,由於您通常希望PHP的請求和響應周期盡可能快,因此可以將其移至下一個,因此PHP不能很好地處理此問題。請求。 您的PHP應用程序應提供對是否以給定間隔觸發任務的外部實用程序的立即是/否響應。
我這樣解決了:
// This will be the testing variable, where in the actual script
// we'll check the response code of file_get_contents
$count = 0;
function funcTwo( &$count ) {
// Here I'd run file_get_contents and parse the headers
$count = ++$count;
echo "functTwo() running $count... \n";
// Here I'll test for response code 429, if true, restart
if ($count !== 5) {
echo "Count only = $count so we're gonna take a nap... \n";
sleep(1);
echo "Waking from sleep $count and rerunning myself... \n";
funcTwo($count);
return;
}
echo "Count finally = $count, exiting funcTwo... \n";
}
// This function does the main work that relies on the successful response from
function funcOne( $count ) {
echo "functOne() running! \n";
// The function will be delayed here until a successful response is returned
funcTwo($count);
echo "Count finally = $count, so now we can finally do the work that \n";
echo "depends on a successful response from funcTwo() \n";
// Do main work
echo "Work done, exiting funcOne and script... \n";
}
funcOne($count);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.