Page 1 of 1

Managing mail queue and cron

Posted: Sat Mar 21, 2009 9:36 am
by everisk
Hi,

I have a script that send a lot of emails from database and cron to make sure that it continues to send even after the script time out or stop running for some reason. However, how do I make sure that the email will not get sent twice? I think it is possible that the script is still running and when cron kicks in the same email might be fetch from database and that person will get the email message twice? Although I might delete the email address after it has been sent to but I think it is still possible that before it was successfully sent to, the cron kicks in and fetch the same email because the sending hasn't finished and therefore the email address hasn't been deleted.

Re: Managing mail queue and cron

Posted: Sat Mar 21, 2009 9:53 am
by Inkyskin
Each time you send an email, set a flag in the database, say email_sent, to 1. Then we you run the script, only send those that are flagged as 0.

Before you do a fresh run, just remember to set them all to 0 again.

Re: Managing mail queue and cron

Posted: Sun Mar 22, 2009 11:37 pm
by everisk
I'm thinking of doing that but there is still a possibility that email is sending and hasn't got to the part where database is updated to 1 yet (it should be updated after the email is sent) but then cron starts and fetch the same email that is sending to prepare for send before the original script updated the database to 1. Is there anyway I can prevent this?

Re: Managing mail queue and cron

Posted: Mon Mar 23, 2009 2:03 am
by Chris Corbyn
everisk wrote:I'm thinking of doing that but there is still a possibility that email is sending and hasn't got to the part where database is updated to 1 yet (it should be updated after the email is sent) but then cron starts and fetch the same email that is sending to prepare for send before the original script updated the database to 1. Is there anyway I can prevent this?
Create a lock file in your cron script:

Code: Select all

$lockfile = '/var/lock/send-emails.lock';
 
if (is_file($lockfile)) {
  exit("Process already running");
} else {
  file_put_contents($lockfile, '1');
}
 
// ... put all your cron script code here ...
 
unlink($lockfile);
 
You can make this more robust by using register_shutdown_function() to remove the lockfile (in case of say, an uncaught Exception).