2012-07-23 62 views
2

假設我的set_time_limit設置爲30秒並且無法更改。我在php中有一個電子郵件腳本,它的運行時間超過30秒(我還沒有達到那個時間標記。)30秒後超時會發生什麼?腳本會停止然後繼續嗎?記錄PHP腳本的實時運行時間

如果不是,我想記錄從腳本循環開始到30秒爲止的經過時間,然後暫停進程然後繼續。

這樣做的好方法是什麼?

更新:我覺得可能工作

function email() 
{ 
    sleep(2); //delays script 2 seconds (time to break script on reset) 

    foreach ($emails as $email): 
     // send individual emails with different content 
     // takes longer than 30 seconds 
    enforeach; 

    // on 28 seconds 
    return email(); //restarts process 
} 
+0

你嘗試過哪些東西? – 2012-07-23 21:44:46

+3

30秒後,將發出致命錯誤,腳本將被終止。 http://php.net/manual/en/function.set-time-limit.php – 2012-07-23 21:45:35

+0

@sixeightzero沒有什麼,我相信..因此,我要求指導。 – CyberJunkie 2012-07-23 21:47:05

回答

1

建議的方法:

function microtime_float() 
{ 
    list($usec, $sec) = explode(" ", microtime()); 
    return ((float)$usec + (float)$sec); 
} 

$time_start = microtime_float(); 
foreach ($emails as $email): 
    // send individual emails with different content 
    // takes longer than 30 seconds 

    $time_curr = microtime_float(); 
    $time = $time_curr - $time_start; 
    if($time > 28){ //if time is bigger than 28 seconds (2 seconds less - just in case) 
     break;// we will continue processing the rest of the emails - next time cron will call the script 
    } 
enforeach; 
+3

如果你有PHP> = 5.0,你可以使用'microtime(true)'作爲浮點檢索。 – 2012-07-23 22:04:52

+0

@PhpMyCoder感謝您的評論。 – alfasin 2012-07-23 22:32:29

1

什麼你問的是不可能的。當達到腳本超時時,它停止。你不能暫停它並繼續它。您只能重新啓動它。讓我告訴你我是如何解決類似問題的。

Part One: 
Queue all your emails into a simple database. (Just a few fields like to, 
from, subject, message, and a flag to track if it is sent.) 

Part Two. 
1. Start script 
2. Set a variable with the start time 
3. Check the db for any mails that have not been sent yet 
4. If you find any start a FOR loop 
5. Check if more than 20 seconds have elapsed (adjust the window here, I like 
    to allow some spare time in case a mail call takes a few seconds longer.) 
6. If too much time passed, exit the loop, go to step 10 
7. Send an email 
8. Mark this email as sent in the db 
9. The FOR loop takes us back to step 4 
10. Exit the script 

每60秒運行一次。它發送了它可以發送的信息,然後下一次發送。

+0

感謝您的建議!我正在考慮類似的方法,但沒有檢查時間。如果我每分鐘都在運行腳本,我不會看到一個點 – CyberJunkie 2012-07-23 23:49:41

+0

這一點是因爲您最初的問題。考慮一下,如果你不檢查時間已過,併發送一封電子郵件,但腳本在電子郵件被標記爲已發送之前中止。該人將收到重複的電子郵件。還要考慮您的主機可能會更改超時值,或者您在另一臺主機上使用該腳本。檢查已經過的時間讓您掌控並讓您提前停止腳本,而不是依靠超時來爲您結束腳本。 – colonelclick 2012-07-24 16:26:21