每秒调用一个PHP函数 [英] Calling A PHP Function Every Second

查看:126
本文介绍了每秒调用一个PHP函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法定期执行功能?

Is there a way to execute a function at regular interval?

我有一个数据库表,我需要知道何时添加或删除条目.试图使用的逻辑是Ajax调用Server,但是服务器没有立即响应,而是连续30秒钟检查数据库是否更新,如果是,则仅检查响应,否则将在30秒钟后响应.这样,我试图通过每秒调用Ajax请求来最小化服务器上​​的负载.

I have a database table and I need to know when an entry is added or removed. The logic am trying to use is Ajax makes a call to Server, but instead of responding immediately, server continuously checks for 30 seconds if database is updated, if yes then only then it responds, else it responds after 30 seconds. This way I am trying to minimize the load on server by calling Ajax requests every second.

我该怎么做?使用while循环有意义吗?像这样的东西-

How do I do this? Does using while loop make sense ? Something like this may be-

while (SomeCondition)
{
   if (CheckIfDatabaseChanged())
   {
      echo "System Updated";
      break;
   }
}

如果这不是一个废话,那么我如何确保循环仅运行30秒并中断.还是有更好的解决方案?

If this is a no non-sense solution then how can I make sure that the loop runs only for 30 seconds and breaks. Or is there a better solution?

推荐答案

您正在考虑的是一种称为长轮询的方法,它在PHP上无法很好地扩展,特别是当您使用阻塞IO时.

What you are thinking off is something called long-polling and it does not scale good on PHP especially when you use blocking IO.

有关更多信息,请参见 https://stackoverflow.com/a/6488569/11926 .

See https://stackoverflow.com/a/6488569/11926 for some more information.

但是您的代码可能看起来像这样

But your code could look something like this

set_timeout_limit(31);
$i=0;
while ($i<30) {
    // poll database for changes which is a bad idea.
    i = i + 1;
    sleep(1); // sleep 1 second
}

我敢打赌,您不能同时运行许多这些.我的建议是使用类似 redis pubsub 通知数据库更改和某种长轮询/Websocket解决方案.

I bet you you can not run many of these concurrent.My advice would be to use something like redis pubsub to notify of db changes and some kind of long-polling/websocket solution instead.

如果可能的话,您应该为数据库更改生成subscribe的后台进程,然后将更改发布至pusher,例如,因为拥有多个长时间运行的进程确实对性能不利.

If possible you should spawn a background process to subscribe to database changes and then publishes changes to pusher for example, because having multiple long running processes is really bad for performance.

您可以自己托管两者,也可以使用托管服务,例如:

You could host both of them yourself or use hosted services like for example:

Redis:

长轮询/Websocket:

他们都有免费的小型计划,当您对这些计划而言太大时,您可以考虑自己托管这些解决方案.

They both have small free plans which could get you started and when you get too big for these plans you could think about hosting these solutions for yourself.

PS :我还在PHP中找到了一种非阻塞解决方案,称为

P.S: I have also found a non-blocking solution in PHP which is called React. This solution might scale(better) in PHP.

这篇关于每秒调用一个PHP函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆