Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
share|improve this question
    
This is much more likely a problem with your PHP script than the cronjob. –  mgorven Aug 27 '12 at 7:08
    
@ashutosh: Do you observe the same behavior if you run the script manually from the shell prompt? –  Khaled Aug 27 '12 at 7:11
    
no the php script working fine, As any possiblity of running multiple instances of cronjob?? –  ashutosh Aug 27 '12 at 7:12
    
@Khaled I tried to run the script manually, surprisingly mail sent only once! –  ashutosh Aug 27 '12 at 7:19
    
That cron table entry means two minutes past each hour, not every two minutes, so you have another entry (or perhaps several) to run it more often? Is there more than one instance of crond running? –  ramruma Aug 27 '12 at 11:38
add comment

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
    
@lain Thanks for your answer, just one more question, to applying locking mechanism u suggested use flock. So what will do file /tmp/myAppLock.lck file, this is file is already exists or I have to create one and what this file exactly do?? –  ashutosh Aug 27 '12 at 7:41
    
The flock program manages that file - you should read the man page I linked to. –  Iain Aug 27 '12 at 7:48
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.