Every day a PHP script is executed by cron job to send emails to subscribers.
The script works fine, But the issue is that the subscribers are increased and The script is timing out after 100 sec.
So I need to run process in batches.
My question: How to let the script to start from a certain id, then the next time start from this id? I cannot divide the script into different files as I don't know how many subscribers there are.
/* Get all subscribers from DB */
$stmt = $pdo->query("SELECT * FROM subscribers");
/* Loop through subscribers and get email */
foreach(){
/* Create a new PHPMailer object. */
$mail = new PHPMailer();
/* Set the mail sender. */
$mail->setFrom('myemail@domain.com', 'John Doe');
/* Add a recipient. */
$mail->addAddress('recipient@recipient.com', 'recipient');
/* Set the subject. */
$mail->Subject = 'New article';
/* Set the mail message body. */
$mail->Body = 'This is a new article.';
/* Finally send the mail. */
if (!$mail->send())
{
/* PHPMailer error. */
echo $mail->ErrorInfo;
}
}
UPDATE:
Would one of these methods work?
1- Instead of fetching all the subscribers at once SELECT * FROM subscribers
, I use a loop to get 500 rows per time and maybe use sleep()
after each time.
/* Loop with increment of 500 */
for($i = 0; $i <= $rowsCount; $i += 500){
/* Select 500 subscribers */
$query = ("SELECT * FROM `subscribers` LIMIT $i, 500");
/* Send Emails to 500 subscribers */
sleep(60);
}
2- Save the last subscriber id in a table and each time the script is executed, Start from that id:
/* Get the last subscriber id from previous time */
$last_subscriber_id = `SELECT id FROM last_subscriber_id`;
/* Select the next 500 subscribers starting from the previous time last id */
$query = "SELECT * FROM `subscribers` WHERE `id` > $last_subscriber_id LIMIT 500";
/* Send Emails to 500 subscribers */
..
/* Update last_subscriber_id with the last id */
..
But in this case I would run the script every x minutes, As I don't know how many subscribers are there
And I don't think I can update the cron job with PHP, So that if all the subscribers received the emails stop executing the script.