私のウェブサイトは、誰かが PM (プライベート メッセージ) を送信するたびに、私のユーザーに電子メールを送信します。「SITE NAMEで誰かがあなたにメッセージを送信しました。ログインして表示してください」という行に沿って何かが表示されます。
現時点では、私のサイトはあまり人気がないので、これを行う私の現在の方法は、パフォーマンスに関して問題はありませんでした:
// code that sends pm here...
// code that stores pm in messages table here...
// notify user by emailing them right away
mail($user_email, $subject, $message);
基本的には、PM が送信されるたびにメール機能が実行され、その場でメッセージが送信されます。したがって、100 件のメッセージが送信されるたびに、mail() が 100 回呼び出されます。
私のサイトの人気が高まり、より多くのユーザーがより多くの PM を訪れるようになると予想しているため、現在の方法ではパフォーマンスの悪夢になると思います。だから私は代わりにこのようにすることを考えていました:
// get the last message that was accounted for by the last cron
$query = mysql_query(" SELECT `last_checked_id` FROM `settings` ");
$last_checked_id = mysql_fetch_array($query);
$user_emails = array();
// get all messages that were added to this table since the last time this cron ran
$query = mysql_query(" SELECT `recipient_id`, `message_id` FROM `messages` WHERE `message_id` > '$last_checked_id' ");
$i = 0;
while($row = mysql_fetch_array($query)) {
if($i == 0) {
// set this as the last message processed
mysql_query(" UPDATE `settings` WHERE `last_checked_id` = '". $row['message_id'] ."' ");
}
// only put this user in the to email list if he hasn't been added already (since there can be multiple messages for the same user but we need to notify him only once)
if(!in_array($row['recipient_id'], $user_emails)) {
array_push($user_emails, $row['recipient_id']);
}
}
$i++;
// send email to all users at one
mail(implode(',', $user_emails), $subject, $message);
このスクリプトを cron として設定し、1 時間ごとに実行することができます。すべての電子メールは一度に送信され、メール関数は 1 回だけ呼び出されます。唯一の欠点は、ユーザーが PM を受信してもすぐには通知されず、1 時間以内に 1 回通知されることです。しかし、それは大したことではなく、私が一緒に暮らすことができるものではありません.
私の質問は次のとおりです。
- cron メソッドの方がパフォーマンスが大幅に優れているか、それとも増加は無視できるか
- これはほとんどの大規模サイトが行う方法ですか? または、より良い方法がありますか、確立されたライブラリのメイバイですか?
ありがとう。