问题
I am on a standard shared Hostgator which has a limit of 500 mails per hour.
I am trying to throttle my email script to only send 1 email per 8 seconds...
$query=mysql_query("SELECT email FROM users WHERE verified='1' ORDER BY balance DESC");
while($arr=mysql_fetch_array($query)){
set_time_limit(30);
$mail->AddAddress($arr[0]);
$mail->Send();
$mail->ClearAddresses();
echo "Sent to ".$arr[0]."<br><br>";
sleep(8);
}
I am using PHPMailer. The script itself works fine, it emails once every 8 seconds...
But the rest of the domain freezes up completely.
Is there an alternative method of sleeping I can use that won't freeze up my whole domain?
Thanks :)
回答1:
Cronjobs cannot be executed secondly, only minutely. */1
in the minute field will run the script every 1 minute, but you cannot get any more granular than that.
There is nothing wrong with the sleep, but do not run the command from your browser. The reason you are locking up the domain is because your Apache thread is held up on the script with sleep. Until it finishes, your requests will be blocked and queued.
I would suggest that you keep your script, and just execute it with a cronjob hourly, or every few hours. How often does it really need to run? Once a day?
The below will run it every night at 5 after midnight, and throw it to the background.
5 0 * * * user php -f /path/to/file &
回答2:
I would recommend using a cron job (Unix) or scheduled task (Windows) to call this script at set duration.
Or use something like Mandrill to handle the sending of bulk emails.
回答3:
This cannot be implemented directly into the script unless it is constantly running and rereads the database after every request.
I would recommend a cron job that is run every 8 seconds then reads the first entry from the database and if it exists, send the email:
- Set up cron job to call script every 8 seconds
- Script queries database for first entry in table
- If data exists, send email based on that data
- Delete the row
- Script ends
回答4:
You're locking up your server with the while loop. Every 8 seconds it executes 1 pass of the loop, then waits for another 8 seconds. Everything else has to wait until it's complete. Try using a cron job.
来源:https://stackoverflow.com/questions/12101082/php-sleep-function-email-throttling-freezes-entire-server