Php – Cron Job Sending Bulk Emails at a time

apache-2.2cronemailPHP

I have developed a PHP script where I want to send automated mails to users. I
successfully implemented a cron job with a PHP script which checks out a PHP mail
queue table for pending mails. The script is working fine, but the cron job is
working strangely: it sends the mail to users, but 3 or 4 at a time. I wanted
to send the mail only once. How can I achieve this?

I use a condition to check whether the mail is sent or not, if it is 0 then it
will send mail and update the value to 1. This condition is working fine. Also
the relative database is showing only one entry per user, so logically only one
email is supposed to be sent to the user, but instead the cron job is sending 3
or 4 same email at a time to user.

I set the cron job for every 2 min. The command is as follows:

2 * * * * wget (Http PATH to SERVER)/Utils/MailQueue.php

Best Answer

If you think that multiple instances of your script may be running at the same time then use some form of locking mechanism. Put your wget in a script and wrap it in a flock command

2 * * * * /usr/bin/flock -n /tmp/myAppLock.lck /path/to/your/wgetscript 

If the MailQueue.php script is on the same machine that you're running cron on then you don't need wget

2 * * * * /usr/bin/flock -n /tmp/myAppLock.lck /usr/bin/php /path/to/Utils/MailQueue.php

will probably be a better solution as it will work without your webserver.