sarrrrek
sarrrrek

Reputation: 148

Run a PHP function every X minutes

I'm currently writting a forum software to learn PHP. I made some sitewide stats section that I cache in my RAM so the SQL won't get called on every pageload.

I plan to update these stats every ten or so minutes.

Is there a way to implement this without cron? It's fine if I need it but without would be better.

Is there some way with the time so that after every X minutes a visitor would be fine to trigger the re-caching?

Upvotes: 1

Views: 12161

Answers (2)

Clemens Basler
Clemens Basler

Reputation: 81

If you need exact timing and the function, you want to execute, takes some time, you can do it like this.

while(true){
$time_pre = microtime(true);

// your code

$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
sleep($time - $exec_time);
}

Upvotes: 0

Michal
Michal

Reputation: 5220

Php scripts can run indefinitelly. You should not want to do this but you can.

set_time_limit(0); // make it run forever
while(true) {
    doSomethingSpecial();
    sleep(300);
}

Use cron instead.

Upvotes: 5

Related Questions