Run a PHP script every second using CLI

You could actually do it in PHP. Write one program which will run for 59 seconds, doing your checks every second, and then terminates. Combine this with a cron job which runs that process every minute and hey presto.

One approach is this:

set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
    doMyThings();
    sleep(1);
}

The only thing you’d probably have to watch out for is the running time of your doMyThings() functions. Even if that’s a fraction of a second, then over 60 iterations, that could add up to cause some problems. If you’re running PHP >= 5.1 (or >= 5.3 on Windows) then you could use time_sleep_until()

$start = microtime(true);
set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
    doMyThings();
    time_sleep_until($start + $i + 1);
}

Leave a Comment