views:

544

answers:

4

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? ...)

+2  A: 

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.

Jason Cohen
+7  A: 
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

SM
Note: will only work in PHP 5.1.3 or newer, and not on Windows.
Chad Birch
Thx, Chad Birch. Simply forgot about this :) Never seen productions server with "heavy load" on win :)
SM
@Chad with PHP < 5.1.3 you can replace sys_getloadavg() with version from my answer: split(' ',file_get_contents('/proc/loadavg'))
vartec
thats what I needed
Nir
+2  A: 

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.

Parrots
+2  A: 

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

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