每天,cron作业都会执行PHP脚本,以向订阅者发送电子邮件。

该脚本可以正常工作,但是问题在于订阅者增加了,并且该脚本在100秒后超时。

所以我需要分批运行流程。

我的问题:如何让脚本从某个ID开始,然后下次从该ID开始?我无法将脚本分为不同的文件,因为我不知道有多少个订阅者。

/* 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;
    }

}


更新:

这些方法中的一种会起作用吗?

1-我不是使用一次获取所有订阅者SELECT * FROM subscribers的方法,而是使用循环每次获取500行,并且可能在每次之后使用sleep()

/* 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-将最后一个订户ID保存在一个表中,每次执行脚本时,从该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 */
..


但是在这种情况下,我将每x分钟运行一次脚本,因为我不知道有多少个订户

而且我认为我无法使用PHP更新cron作业,因此,如果所有订阅者都收到了电子邮件,则停止执行该脚本。

最佳答案

我建议一些可能的方法。

一种是remove lines from the file as you process it

另一个方法是使用KafkaRabbitMQ之类的系统异步执行此操作。

最后,您可以在持久性存储中记录要处理的行号,读取该行号,然后跳转到文件的该行。

关于php - 将大量消息发送给订阅者到时事通讯,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57415082/

10-11 07:01