Calling A PHP Function Every Second

后端 未结 2 1991
面向向阳花
面向向阳花 2021-01-06 07:20

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

I have a database table and I need to know when an entry is added or removed. The logic am trying to use is

相关标签:
2条回答
  • 2021-01-06 07:57

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

    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
    }
    

    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.

    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:

    • http://redistogo.com

    Long-polling / Websocket:

    • http://pusher.com

    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.


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

    0 讨论(0)
  • 2021-01-06 07:59

    Use this:

    set_timeout_limit(0)
    

    http://se.php.net/manual/ru/function.set-time-limit.php

    0 讨论(0)
提交回复
热议问题