Managing mail queue and cron

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
everisk
Forum Newbie
Posts: 11
Joined: Sat Mar 21, 2009 9:32 am

Managing mail queue and cron

Post 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.
User avatar
Inkyskin
Forum Contributor
Posts: 282
Joined: Mon Nov 19, 2007 10:15 am
Location: UK

Re: Managing mail queue and cron

Post 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.
everisk
Forum Newbie
Posts: 11
Joined: Sat Mar 21, 2009 9:32 am

Re: Managing mail queue and cron

Post 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?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Managing mail queue and cron

Post 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).
Post Reply