Reputation: 4212
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 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.
How do I do this? Does using while
loop make sense ? Something like this may be-
while (SomeCondition)
{
if (CheckIfDatabaseChanged())
{
echo "System Updated";
break;
}
}
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?
Upvotes: 4
Views: 14345
Reputation: 61771
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:
Long-polling / 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.
P.S: I have also found a non-blocking solution in PHP which is called React. This solution might scale(better) in PHP.
Upvotes: 7
Reputation: 1730
Use this:
set_timeout_limit(0)
http://se.php.net/manual/ru/function.set-time-limit.php
Upvotes: 0