【发布时间】:2019-12-16 07:28:46
【问题描述】:
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 作业,所以如果所有订阅者都收到了电子邮件,则停止执行脚本。
【问题讨论】:
-
欢迎来到 SO!请包含一些您已经完成的代码,否则您的问题可能会被标记。有关更多信息,请参阅stackoverflow.com/tour
-
我不认为代码在这里很重要,我有一个数据库,我得到记录然后给他们发送电子邮件
-
我仍然建议您编辑问题,使其包含足够的详细信息(哪个数据库?您到底尝试了什么?什么服务器架构?哪个操作系统?为什么在 PHP 中这样做? )。
-
我添加了一些代码,数据库是 MYSQL,它是一个 Cpanel,我使用 PHP 这样做是因为我有使用 PHP 的经验
-
您确实应该将大量电子邮件发送给专家服务。 DIY 工作有陷入黑洞的风险。
标签: php mysql cron subscription