Reputation: 1293
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?
Upvotes: 0
Views: 9734
Reputation:
$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.
Upvotes: 0
Reputation: 1293
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);
}
?>
Upvotes: 1
Reputation: 2337
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.
Upvotes: -1
Reputation: 3747
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.
Upvotes: 0
Reputation: 59987
Why not modify the script so that it just repeats the code every second? This will reduce the parsing overhead and be less complicated.
Upvotes: 0