Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js + setInterval = Connection lost: The server closed the connection

Node.js + setInterval = Connection lost: The server closed the connection

Problem

I have a simple Node.JS script (just a script, no server), which is supposed to do a thing every 24 hours. But after about 8 hours I see this in the error log:

Error: Connection lost: The server closed the connection.
    at Protocol.end (/home/user/dev/app/node_modules/mysql/lib/protocol/Protocol.js:73:13)
    at Socket.onend (stream.js:79:10)
    at Socket.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:910:16
    at process._tickCallback (node.js:415:13)
error: Forever detected script exited with code: 8
error: Forever restarting script for 1 time

I'm sure this is stupid and it's an easy fix, but I just can't find it yet. Any ideas?

Problem courtesy of: Nikolay Dyankov

Solution

Looks like you're keeping an open Connection to a remote MySQL server. The remote server is closing the connection after 8 hours of idle connection. So you have two options. Either you send a keepalive request or you disconnect after your initial request and then open the connection again when timer initiates the next event.

Keepalive

If you want to send a keepalive request, simply setup a select 1 on an interval timer.

select 1 is just a simple query that will cause MySQL to return a result of 1 and reset the MySQL server's connection timeout. It would look something like this.

function keepalive() {
  connection.query('select 1', [], function(err, result) {
    if(err) return console.log(err);
    // Successul keepalive
  });
}
setInterval(keepalive, 1000*60*5);

Pooling

However, you're better off using the mysql module's pool functionality. It will connect to the MySQL server on an as-needed basis and will handle disconnects for you automatically.

Solution courtesy of: Daniel

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js + setInterval = Connection lost: The server closed the connection

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×