简体   繁体   中英

Stop foreach Loop for limited time span in php

I am sending emails to users using sendgrid email delivery service.

Below is my code, which send emails to all users of a website.

foreach($resident_emails as $email){
     $this->load->model('email_model');
     $this->load->model('preferences_model');
     $user_email = $email->email;
     $admin_email = $from_email;
     $email_row = array('from_email'=>$admin_email,'from_name'=>$from_name,'message'=>$newsletter,'subject'=>$subject);
     $arr_var = array('subject'=>$subject,'message'=>$newsletter);
     $this->email_model->sendEmail($user_email,$email_row,$arr_var);
 }

Now for example i have to send email to more than 200 users.

Problem

But problem is that, only 10 emails are delivered, and for remaning i received ' FAILED ' status.

Question

My question is, how can i stop the execution of foreach loop for 10 seconds or more, and then after certain time, next 10 emails sent, and so on?

PHP provide in-built function sleep():

foreach($resident_emails as $email){
     $this->load->model('email_model');
     $this->load->model('preferences_model');
     $user_email = $email->email;
     $admin_email = $from_email;
     $email_row = array('from_email'=>$admin_email,'from_name'=>$from_name,'message'=>$newsletter,'subject'=>$subject);
     $arr_var = array('subject'=>$subject,'message'=>$newsletter);
     $this->email_model->sendEmail($user_email,$email_row,$arr_var);
     sleep(10);
 }

If you really want to wait 10 seconds before re-sending a couple of more emails, you can use the sleep-function provided by php:

$i = 0;
foreach($resident_emails as $email){
    $this->load->model('email_model');
    $this->load->model('preferences_model');
    $user_email = $email->email;
    $admin_email = $from_email;
    $email_row = array('from_email'=>$admin_email,'from_name'=>$from_name,'message'=>$newsletter,'subject'=>$subject);
    $arr_var = array('subject'=>$subject,'message'=>$newsletter);
    $this->email_model->sendEmail($user_email,$email_row,$arr_var);
    $i++;

    // check if this is the nth iteration
    if($i == 10) {
        $i = 0;
        sleep(10);
    }
}

In the above example, we send 10 emails. On the next iteration, we wait 10 seconds before resending another 10 mails... and so on.

I highly doubt that this will solve your problem, though. Keep in mind that always waiting for 10 seconds raises the execution time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM