开发者

breaking loop process into parts by delaying them, need advice

开发者 https://www.devze.com 2023-03-01 12:53 出处:网络
i wanted to break down a process (loop) into some parts, for example if have 128 emails to send : function subs_emails(){

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{
        re开发者_运维技巧turn false;
    }
}

will this works ?? or is there any other "better approach" solution ?? need advice please

thanks


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() 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:

  1. Script executes every 10mins
  2. Load 15 subscribers who have not been flagged as already notified
  3. Loop through all 15 loaded subscribers and send each an email
  4. Set flag on all 15 to say they have been sent the email
  5. Script will then run 10mins later to process the next 15 subscribers
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号