php foreach每100次睡眠然后继续

时间:2014-01-11 18:49:19

标签: php foreach sleep

我的站点中有一个foreach循环和5000个用户 我想给他们发电子邮件

每10名成员睡5秒然后继续

$headers   = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: Sender Name <sender@domain.com>";
$headers[] = "Bcc: JJ Chong <bcc@domain2.com>";
$headers[] = "Reply-To: Recipient Name <receiver@domain3.com>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

$users = array('mohamed','ahmed');
foreach($users as $user){
mail($user, $subject, $email, implode("\r\n", $headers));
}

怎么做

2 个答案:

答案 0 :(得分:13)

使用模数运算符检测10的倍数。

foreach ($users as $i => $user) {
    mail($user, $subject, $email, implode("\r\n", $headers));
    if ($i > 0 && $i % 10 == 0) {
        sleep(5);
    }
}

答案 1 :(得分:5)

$count=0;
foreach($users as $user){
    $count++;
    mail($user, $subject, $email, implode("\r\n", $headers));
    if(($count%10)==0)
    {
        sleep(5);
    }
}