通过延迟将循环过程分成几个部分,需要建议
我想将一个流程(循环)分解为几个部分,例如,如果有 128 封电子邮件要发送:
function subs_emails(){
$subscribers = //find subscribers
if(!empty($subscribers )){
foreach($subscribers as $i => $subscriber){
sendEmail($subscriber->id);
if($i % 15 == 0){ //<-- send email per 15
sleep(60); //to pause the process for 60 seconds
}
}
return true;
}else{
return false;
}
}
这可行吗?或者还有其他“更好的方法”解决方案吗?需要建议,
谢谢
i wanted to break down a process (loop) into some parts, for example if have 128 emails to send :
function subs_emails(){
$subscribers = //find subscribers
if(!empty($subscribers )){
foreach($subscribers as $i => $subscriber){
sendEmail($subscriber->id);
if($i % 15 == 0){ //<-- send email per 15
sleep(60); //to pause the process for 60 seconds
}
}
return true;
}else{
return false;
}
}
will this works ?? or is there any other "better approach" solution ?? need advice please
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常的方法是一次只发送几封电子邮件,并在后台标记已发送的电子邮件(例如通过数据库标志 send=1)
然后通过 cronjob 每隔几分钟调用一次脚本
这样您就不会遇到 php 问题向大量订阅者发送电子邮件时超时
The usual approach would be to send only a few emails at once and mark the sent ones on the background(via database flag sent=1 for example)
Then call the script every few minutes via a cronjob
This way you dont run into problems with php timeouts when sending emails to a lot of subscribers
sleep() 将导致脚本停止定义的秒数(在您的示例中为 60 秒)。它不会真正打破循环,而只是延迟循环。
一种可能的解决方案是记下已向哪个订阅者发送电子邮件。然后,您可以通过 cron 定期执行脚本,并且仅加载少量尚未收到电子邮件的脚本。例如:
sleep() will cause the script to stall for the defined number of seconds (60 in your example). It won't really be breaking the loop but instead merely delaying it.
A possible solution is to make a note of which subscriber has already been sent an email. Then you can have your script execute at regular intervals via cron and only load a small amount of those who have not yet been sent an email. For example: