PHP function call every second

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

I have a database table and I need to know when a record will be added or deleted. The logic I'm trying to use is that Ajax makes a call to the server, but instead of immediately responding, the server continuously checks for 30 seconds, if the database is updated, if so, then only it answers, otherwise it reacts after 30 seconds. Thus, I try to minimize the load on the server by calling Ajax requests every second.

How can I do it? Does it make sense to use a while ? Something like this might be

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

If this is not a meaningless solution, then how can I make sure that the cycle only works for 30 seconds and breaks. Or is there a better solution?

+4
source share
2 answers

What you think of something called long-polling and it does not scale in PHP, especially when you use IO locking.

See fooobar.com/questions/1419362 / ... for more details.

But your code might 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 can't run many of these parallel ones. My advice would be to use something like redis pubsub to notify you of changes to db and some kind of long-poll / websocket solution.

If possible, you should create a background process in subscribe to modify the database and then, for example, post the changes to pusher , since having several long processes is really bad for performance.

You can host both of them yourself or use public services, for example, for example:

Redis:

Long-poll / Websocket:

Both of them have small free plans that can get you started, and when you are too big for these plans, you can think about placing these solutions for yourself.


PS . I also found a non-blocking solution in PHP called React . This solution can scale (better) in PHP.

+7
source
0
source

All Articles