0

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 an event every second.

I wanted to use a cronjob but with cron you can run a script only every minute.

My idea was to use cron and loop 60 times in my php script. But I think this isn't the best solution.

So whats the best way to run a script every second?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Shylux
  • 1,163
  • 2
  • 16
  • 31
  • 1
    Take a look at this: http://superuser.com/questions/342830/cron-alternative-with-timeouts-and-second-resolution . – ldiqual Jan 13 '12 at 08:20
  • 3
    Possible duplicate of: http://stackoverflow.com/questions/1726116/run-a-php-script-every-second-using-cli – Sebastian Wramba Jan 13 '12 at 08:21
  • I think you're looking for the wrong solution to your problem, which seems to ask for a fundamentally different architecture than you're used to. What are you trying to accomplish? – deceze Jan 13 '12 at 08:37
  • OK, so what kind of events may happen? Something that needs immediate action? In that case PHP is not really a great language for the project. Or just something that the user will see the next time he contacts the server? Then there's no need to *actually* do it every second. – deceze Jan 13 '12 at 09:13
  • cron every second? what is it that you're trying to achieve? you should tell us why would you want to do this? as for cron the smallest interval is 1 minute. – strike_noir Jan 13 '12 at 08:21

5 Answers5

1

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);
}
?>
Shylux
  • 1,163
  • 2
  • 16
  • 31
0
$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

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

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

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.

dar7yl
  • 3,727
  • 25
  • 20
0

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.

Stefan Koenen
  • 2,289
  • 2
  • 20
  • 32