对于我的网站,我每30分钟就有一次Cron Jobs运行,如果我尝试在这30分钟的时间内访问我的网站,我会得到500内部服务器错误,或者我在任何页面上获得5-10秒的加载时间现场。
我正在使用Php,而我的cron作业正在使用Php和MySQL。
我该如何制作,以便它不会滞后我的整个网站或更快,所以滞后更少?
Crons:
其中一个每15分钟运行一次的crons:
<?php
require('functions.php');
global $mysqli;
$select = $mysqli->prepare("SELECT `tkn` FROM `users` ORDER BY `dt` ASC LIMIT 0, 200");
$select->execute();
$select->bind_result($cur_token);
$tokens = array();
while($select->fetch())
{
array_push($tokens, $cur_token);
}
foreach($tokens as $token)
{
$api = Class::Instance($token);
$info = $api->Users->Info();
if(empty($info->error))
{
$info->data->token = $token;
updateUser($info->data);
} else if($info->error->code == 400) {
$update = $mysqli->prepare("UPDATE `users` SET `active` = 0 WHERE `tkn` = ?");
$update->bind_param('s', $token);
$update->execute();
}
}
?>
其他Cron工作:
<?php
require('functions.php');
global $mysqli;
$select = $mysqli->prepare("SELECT `email`, `username`, `id` FROM `users` WHERE `email` IS NOT NULL AND `email` <> '' AND `credits` < `credits_offered` AND `emailed_credits` = 0");
$select->execute();
$select->bind_result($email, $username, $id);
$users = array();
while($select->fetch())
{
$users[] = array("id" => $id, "email" => $email, "username" => $username);
}
foreach($users as $user)
{
$to = $user['email'];
$subject = '';
$message = "";
$headers = 'From: email@domain.com' . "\r\n" .
'Reply-To: reply@domain.com';
mail($to, $subject, $message, $headers);
$update = $mysqli->prepare("UPDATE `users` SET `emailed` = 1 WHERE `id` = ?");
$update->bind_param('i', &$user['id']);
$update->execute();
$update->close();
}
?>
答案 0 :(得分:2)
第一个建议是将准备调用移出循环。更新将锁定您的表一段时间,所以只有在完成操作后更新...缓存需要在数组中更新并启动事务,执行除提交之外的所有更新。 已更新邮件脚本的代码示例
<?php
require('functions.php');
global $mysqli;
$select = $mysqli->prepare("SELECT `email`, `username`, `id` FROM `users` WHERE `email` IS NOT NULL AND `email` <> '' AND `credits` < `credits_offered` AND `emailed_credits` = 0");
$select->execute();
$select->bind_result($email, $username, $id);
$users = array();
while($select->fetch())
{
$users[] = array("id" => $id, "email" => $email, "username" => $username);
}
$u = array();
foreach($users as $user)
{
$to = $user['email'];
$subject = '';
$message = "";
$headers = 'From: email@domain.com' . "\r\n" .
'Reply-To: reply@domain.com';
mail($to, $subject, $message, $headers);
$u[] = $user['id'];
}
$update = $mysqli->prepare("UPDATE `users` SET `emailed` = 1 WHERE `id` = ?");
$update->bind_param('i', &$i);
$mysqli->autocommit(false);
foreach($u as $i)
$update->execute();
$update->close();
$mysqli->commit();
哦,差点忘了,大多数mysql存储引擎都非常愚蠢,请确保你使用InnoDB,那个拥有事务支持。或者,如果您使用“愚蠢”的存储引擎,如果您的users.id是通过执行操作,您仍然可以欺骗它使单个事务更新多行
$update = $mysqli->prepare('UPDATE users SET emailed=1 WHERE id IN (' . implode(',', $u) . ')');
$update->execute();
$update->close();
关闭foreach($users as $user)
语句后
答案 1 :(得分:-5)
编写更高效的脚本或获得更好的硬件。
编辑:
就批量电子邮件发送而言,您可以为脚本添加超时,以便它不会尽快完成所有电子邮件。这样可以减少CPU上的负载,但会缩短脚本的使用时间。
例如:
for(all emails)
{
//send email
sleep(5);
}