Run a PHP script every second using CLI

大憨熊 提交于 2019-11-27 03:40:35
nickf

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);
}

Have you thought about using "watch"?

watch -n 1 /path/to/phpfile.php

Just start it once and it will keep going. This way it is immune to PHP crashing (not that it happens, but you never know). You can even add this inittab to make it completely bullet-proof.

jW.

Why not run a cron to do this and in the php file loop 60 times which a short sleep. That is the way I have overcome this to run a php script 5 times a minute.

To set up your file to be run as a script add the path to the your PHP on the first line such as a perl script

#!/user/bin/php
<?php
    while($i < 60) {
      sleep(1);
      //do stuff
      $i++;
    }
?>

This is simple upgraded version of nickf second solution witch allow to specify the desired interval in seconds beetween each executions in execution time.

$duration = 60; // Duration of the loop in seconds
$sleep = 5; // Sleep beetween each execution (with stuff execution)

for ($i = 0; $i < floor($duration / $sleep); ++$i) {
    $start = microtime(true);

    // Do you stuff here

    time_sleep_until($start + $sleep);
}
degenerate

I noticed that the OP edited the answer to give his solution. This solution did not work on my box (the path to PHP is incorrect and the PHP syntax is not correct)

This version worked (save as whatever.sh and chmod +X whatever.sh so it can execute)

#!/usr/bin/php
<?php
$start = microtime(true);
set_time_limit(60);
for ($i = 0; $i < 59; ++$i) {
    echo $i;
    time_sleep_until($start + $i + 1);
}
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!