简体   繁体   English

每X分钟运行一次PHP函数

[英]Run a PHP function every X minutes

I'm currently writting a forum software to learn PHP. 我目前正在编写一个论坛软件来学习PHP。 I made some sitewide stats section that I cache in my RAM so the SQL won't get called on every pageload. 我做了一些站点范围的统计信息部分,将其缓存在RAM中,这样就不会在每次页面加载时都调用SQL。

I plan to update these stats every ten or so minutes. 我计划每十分钟更新一次这些统计信息。

Is there a way to implement this without cron? 有没有办法不用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? 时间是否有办法让每隔X分钟访问一次的访客可以触发重新缓存?

Php scripts can run indefinitelly. php脚本可以无限期运行。 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. 使用cron代替。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM