2

假设我set_time_limit的设置为 30 秒且无法更改。我在 php 中有一个电子邮件脚本,它将在 1 个 cron 作业上运行超过 30 秒(我还没有达到那个时间标记。) 30 秒后超时会发生什么?脚本会停止然后继续吗?

如果没有,我想记录从脚本循环开始到达到 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
}
4

2 回答 2

1

Suggested approach:

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;
于 2012-07-23T21:49:23.057 回答
1

What you ask is not possible. When the script timeout is reached, it stops. You cannot pause it and continue it. You can only restart it. Let me tell you what I did to solve a similar problem.

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

Run this every 60 seconds. It sends what it can, then the rest gets sent next time.

于 2012-07-23T22:10:01.250 回答