【发布时间】:2017-02-21 01:49:01
【问题描述】:
我正在尝试使用 PHP 创建一个网站监控 webapp。要监控的网站的 URL 存储在 MySQL 表中。每分钟都会通过 cron 运行一个脚本 - 它遍历所有网站和 foreach URL,它使用 CURL 访问该站点并使用 CURLINFO_HTTP_CODE 获取 HTTP 代码 - 如果网站已启动,则返回 true,否则返回 false。
脚本运行正常 - 运行一两个网站需要几毫秒,但运行 20 个网站平均需要 2-15 秒。我可以看到,当添加更多站点时,这会导致问题 - 理想情况下,我需要监控数千个站点,并且用户能够添加自己的站点。
当用户添加要监视的站点时,我考虑过为每个 URL 添加单独的 cron 和文件 - 但是我不知道如何去做,我可以预见一些问题,因为我在共享服务器上工作.
那么我应该怎么做呢,或者有没有更好的方法我没有想到?
<?php
function visit($url) {
// VISITS WEBSITE - RETURNS TRUE IF SITE UP, FALSE IF DOWN
}
// GETS THE MONITOR DETAILS FROM DATABASE
$monitor = new Table($monitorInstance);
$all_monitors = $monitor->get('monitors');
$monitors = $monitor->tableData();
//LOOP THROUGH ALL MONITORS
foreach ($monitors as $monitor1) {
$id = $monitor1->id; //GETS ID
$website = $monitor1->url; //GETS URL
$status = $monitor1->status; //GETS STATUS - 'up' or 'down'
// RUNS FUNCTION
if (visit($website)) {
$new_status = 'up';
} else {
$new_status = 'down';
}
// IF STATUS CHANGE UPDATE THE DATABASE
if ($new_status != $status) {
try {
//update the database with the new status
$monitor->update('monitors', $id, array(
'status' => $new_status,
));
} catch(Exception $e) { //catch exceptions
die($e->getMessage());
}
// ALSO SEND EMAIL TO USER
}
}
【问题讨论】:
-
it uses CURL to visit the site and fetch the HTTP code - it returns true if the website is up and false if not为什么不只卷曲标题并检查 http-status-code 而不是获取页面的全部内容? -
为什么不用
update和monitors一次性包含所有新值,而不是执行多 sql 查询? -
你为什么不看看你可以同时做请求的多卷曲
-
@JustOnUnderMillions 说了什么
-
我只在标题上使用 curl - 道歉并编辑了问题以使其更清楚。我将研究 multi curl 同时发出请求 - 谢谢@frz3993。
标签: php performance cron