Let’s say i was writing an aplication where’d i’d need to get notifications in real time from a server, and let’s say those notifications are stored on a mysql database.
For me to get them i’d have to keep polling the mysql server (keep repeating the same select
query till i actually get results) but i figure that is very unefficient way of doing it since most of the time the select would turn up empty . If i do it often it’s unreasonable strain on the server if i do it rarely the notifications would come in very late.
So i was wondering if there is a way for say a mysql query to block until a result matching a condition becomes available.
list = query ("SELECT * FROM `notifications` WHERE `unread`=1") ;
instead of returning an empty list if there is no unread notifications , it would instead wait till there actually are unread notifications to return
I recommend using the producer consumer pattern, implemented with a new table as the “work queue”. There is no need for a stored procedure, because the trigger is so simple.
Create a table with the id of the
notificationto be processed and a “processing status” column, for example:Create a simple trigger that populates a the work queue table:
Your code would have the pseudo code:
select * from work_queue where status = 'ready' order by id limit 1update work_queue set status = 'processing' where id = <row.id>notifications where id = <row.notification_id>delete from work_queue where id = <row.id>orupdate work_queue set status = 'failed' where id = <row.id>(you’ll have to figure out what to do with failed items)If you have a single process polling, there is no need for locking worries. If you have multiple processes polling, you’ll need to handle race conditions.