My website sends an email out to my user's whenever someone PM's (Private Message) them. It says something along the lines of "Someone just sent you a message on SITE NAME, login to view it".
At the moment my site isn't very popular so my current way of doing this hasn't been a problem performance wise:
// 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);
Basically every time a PM is sent, the mail function is executed and the message is sent right there on the spot. So for every 100 messages sent the mail() gets called 100 times.
I am anticipating my site getting more popular and with more users come more PM's so I think my current way of doing it would become a performance nightmare. So I was thinking of doing it this way instead :
// 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);
I can set this script up as a cron and have it run every hour. All the emails are sent in one go with the mail function being called only once. The only drawback is user's aren't notified right away when they recieve a PM, but once within the hour. But that's not a big deal and something I can live with.
My questions are:
- is the cron method significantly better performance wise or is the increase negligable
- is this the way most big sites do it? or is there a better way, some established library maybye?
Thanks.