How do i run a php script every second?

后端 未结 5 1843
醉话见心
醉话见心 2020-12-20 08:51

I am currently writing a online game. Now I have to check if an event happen (checking timestamp in database) and depending on that execute some actions. I have to check for

相关标签:
5条回答
  • 2020-12-20 09:38

    I searched for a better solution but it seems that my first idea, with clean code, is the best solution.

    This is my current code:

    <?php
    set_time_limit(60);
    $start = time();
    
    for ($i = 0; $i < 59; ++$i) {
        // Do whatever you want here
        time_sleep_until($start + $i + 1);
    }
    ?>
    
    0 讨论(0)
  • 2020-12-20 09:41

    Why not modify the script so that it just repeats the code every second? This will reduce the parsing overhead and be less complicated.

    0 讨论(0)
  • 2020-12-20 09:45
    $total_time = 0;
    $start_time = microtime(true);
    while($total_time < 60)
      {
            //DoSomethingHere;
        echo $total_time."\n";
        //sleep(5);
      $total_time =  microtime(true) - $start_time ;
      } 
    

    add this in crontab to run every minute.

    0 讨论(0)
  • 2020-12-20 09:48

    You should probably run the script once, and use a loop with delay to accomplish your desired timing. The side benefit is that this is more efficient, and you would only have to open resources (ie, databases) once.

    0 讨论(0)
  • 2020-12-20 09:49

    You shouldn't want this :P. No host will accept your cronjob is running every second every minute? You can save the time it runned in a database, and the next time you run it calculate the time between both runs and do the calculations you want. every second is a very bad idea.

    0 讨论(0)
提交回复
热议问题