简体   繁体   中英

How can my PHP script tell whether the server is busy?

I want to run a cron job that does cleanup that takes a lot of CPU and Mysql resources. I want it to run only if the server is not relatively busy.

What is the simplest way to determine that from PHP? (for example, is there a query that returns how many queries were done in the last minute? ...)

if (function_exists('sys_getloadavg')) {
    $load = sys_getloadavg();
    if ($load[0] > 80) {
       header('HTTP/1.1 503 Too busy, try again later');
       die('Server too busy. Please try again later.');
    }
}

Try to update this function to your needs

On Linux you can get load from /proc/loadavg file.

$load = split(' ',file_get_contents('/proc/loadavg'))
$loadAvg = $load[0]

If this is a Unix system, parse the output of uptime . This shows the CPU load which is generally considered to be a good measure of "busy." Anything near or over 1.0 means "completely busy."

There are three CPU "load" times in that output giving the load average over 1, 5, and 15 minutes. Pick whichever makes sense for your script. Definition of "load" is here .

You can probably use the info in the Mysql List Processes function to see how many are active vs. sleeping, a decent indicator about the load on the DB.

If you're on Linux you can use the Sys GetLoadAvg function to see the overall system load.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM