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.
Managing mail queue and cron
Moderator: General Moderators
Re: Managing mail queue and cron
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.
Before you do a fresh run, just remember to set them all to 0 again.
Re: Managing mail queue and cron
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?
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Re: Managing mail queue and cron
Create a lock file in your cron script: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?
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);