Run a PHP script every second using CLI

38,769

Solution 1

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

Solution 2

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.

Solution 3

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++;
    }
?>

Solution 4

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

Solution 5

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);
}
?>
Share:
38,769
Saif Bechan
Author by

Saif Bechan

I am a Full Stack Web Developer with industry experience building websites and web applications. I specialize in JavaScript and have professional experience in working with PHP, Symfony, NodeJS, React, Redux and Apollo GraphQL. To ensure high quality and standards I have extensive knowledge on CI/CD pipelines such as GitLab CI and testing frameworks such as JUnit, PHPUnit and Cypress.

Updated on July 14, 2021

Comments

  • Saif Bechan
    Saif Bechan almost 3 years

    I have a dedicated server running Cent OS with a Parallel PLESK panel. I need to run a PHP script every second to update my database. These is no alternative way time-wise, it needs to be updated every second.

    I can find my script using the URL http://www.somesite.com/phpfile.php?key=123.

    Can the file be executed locally every second? Like phpfile.php?

    Update:

    It has been a few months since I added this question. I ended up using the following code:

    #!/user/bin/php
    <?php
    $start = microtime(true);
    set_time_limit(60);
    for ($i = 0; $i < 59; ++$i) {
        doMyThings();
        time_sleep_until($start + $i + 1);
    }
    ?>
    

    My cronjob is set to every minute. I have been running this for some time now in a test environment, and it has worked great. It is really super fast, and I see no increase in CPU nor Memory usage.

  • Saif Bechan
    Saif Bechan over 14 years
    HI, thank you for the quick response. I was thinking of the same thing, but doesn't this method use more cpu power and memory usage. And i dont know how to change the default php settings for my domain. I assume it has a limited execusion time.
  • Saif Bechan
    Saif Bechan over 14 years
    Doesn't this method consume more cpu power or memory usage
  • nickf
    nickf over 14 years
    set_time_limit will change the execution time, and is usually not blocked by hosts in my experience.
  • Saif Bechan
    Saif Bechan over 14 years
    Can you help me with setting up this Cronjob every minute. Do i do this in PLESK or some other place.
  • Saif Bechan
    Saif Bechan over 14 years
    What do you mean with run the file as a script?
  • nickf
    nickf over 14 years
  • JW.
    JW. over 14 years
    No, sleeping will almost certainly use less CPU than re-loading the PHP interpreter every second.
  • Nemoden
    Nemoden almost 12 years
    I actually like this solution more than accepted one and the others which are share the same idea.
  • Admin
    Admin over 10 years
    how can i make it run every 5 seconds ? ++$i is for +1 pre-incrementing., how can i pre-increment by 5 ?, 5+$i isnt working .
  • Tim Hallman
    Tim Hallman over 10 years
    This answer is very helpful, especially the second part. For those wondering why someone wants to run a cron so often; consider my situation, I need to poll trading market data every 2 seconds via an api. The second half of this answer is especially useful, as sometimes the php script which makes the api request will run over 2 seconds if the remote server is busy.
  • Ifnot
    Ifnot over 9 years
    You should also know that set_time_limit is not counting sleeping time with sleep with a linux system. So example will not stop with set_time_limit. See : stackoverflow.com/questions/740954/…
  • Stephen Ngethe
    Stephen Ngethe almost 9 years
    Hi Milan, I have tried googling on how to use watch -n 1 but no results shows up. I would be happy if you could give some pointers Thanks
  • Miguel Stevens
    Miguel Stevens about 8 years
    Do you have more information on this command? Where do you issue it?
  • neophyte
    neophyte over 6 years
  • Flame
    Flame over 4 years
    Note that this may add up to > 60 seconds since your script will take up some time as well. This would then cause the next cron job to overlay with the previous execution.