Arun
Arun

Reputation: 3721

Is there a better way to listen table changes in Node JS without using setInterval() function

I am learning Node JS integration with Codeigniter. The process is working perfect.

I am showing some real time notification when some changes occur in the database(MySql)

Right now I am using setInterval() function with a time of 5 seconds. This will call the DB query in each 5 seconds.

Is there a better way to listen to DB changes without the setInterval() functionality?

My code sample is

io.on('connection', function(socket){
    setInterval(check_new_notification, 5000);
});

socket.on('check_new_notification', function(user,time){
    check_new_notification(user,time);
});

function check_new_notification(user,time){
    if(user == '' || typeof user == 'undefined' || user == null){
        user = user_id;
    }
    if(time == '' || typeof time == 'undefined'){
        time=0;
    }
    if(user != '' && typeof user != 'undefined' && user != null){
        db.getDetails(user,time,mysql,pool,function(error,result,row_count){
            io.emit('trigger_alert',result, row_count);
        });
    }
}

Please let me know if there is a better way to listen to DB changes. Any help could be appreciated.

Upvotes: 1

Views: 802

Answers (2)

DanielKhan
DanielKhan

Reputation: 1208

There is no way to avoid active polling in your case. So your approach is basically correct.

To improve performance, do the following:

  • Create a table with a boolean field status
  • Set status to true if something notification-worthy happened
  • Read status in Node.js
  • If true: Do the select and set status to false
  • If false: Do nothing

Make sure, that your operations are atomic -> Use Transactions.

Upvotes: 1

Jonas Köritz
Jonas Köritz

Reputation: 2644

You should implement the notification functionality where the notification is beeing created. For example, have your application push a message to a queue when the database row has been inserted. Your application may then subscribe to the queue and update when a new row has been inserted. Optionally you could send your complete notification through your message queue.

Upvotes: 0

Related Questions