I have a website which sends daily writing reminders to its users based on their timezone and hour settings. eg: a user in New York (America/New_York) prefers to receive his reminder at 9PM. in my current implementation (after many changes), I store timezone and notify_hour in settings table and find users with a complex and heavy MySQL query.
The query was too slow, I added indexes and it made it faster. After I find the users I try to send the emails through an external smtp server (sendgrid.com). Ive set the cron job to run every 10 minutes and check for 200 users. I have about 2000 active users. It works fine like this. Most of my users are l开发者_如何学JAVAocated in Iran (Asia/Tehran) and most of them have selected 9PM to receive to reminder. so the peak hour is between 8PM and 11PM IRST.
But the server admin says that my cron job uses too much CPU. about 25% which is High. I tried to debug my script, they query itself is fast but when it comes to sending emails through an smtp server, it takes longer:
Email Reminder has been sent to 4 People - Query: 0.75444 Seconds
---- System: 11.18443 Seconds. ----
Email Reminder has been sent to 0 People - Query: 0.65488 Seconds
---- System: 0.68821 Seconds. ----
Email Reminder has been sent to 5 People - Query: 0.75551 Seconds
---- System: 3.45176 Seconds. ----
Email Reminder has been sent to 1 People - Query: 2.37117 Seconds
---- System: 9.05586 Seconds. ----
first number is how long query took and the second is the time for the whole system to load.
this is the script I use for cron job: http://pastebin.com/Eee3Lzys
mailer class connects to smtp server on construction and sends an email on each iteration of the script. (sorry for my English!)Can you suggest a better way to achieve the whole thing or minimizing the cpu usage or something?
Thanks.Please do not insert in loop
foreach($users as $k => $v){
Use multi raw insert that will be fast other than this sql query pefomance depends on the data on your live server.
精彩评论