0

I have this function and it's called during my node server starts up in index.js file. In the init function, it sets setInterval to call refreshKeyValues periodically which takes about 10 sec. I ran some tests and sent a health check (simple get call to health end point returning 200 ok) and it seemed that the health check blocked when refreshKeyValues was running. Is setInterval blocking? How do I make this refreshing logic running on background so that it won't block the incoming requests?

export default function initMyClient(server) {
  server.clients.myclient = MyClient.createNewClient();
  server.clients.myclient.init();
  server.keyValues = getKeyValues();
  function refreshKeyValues() {
    server.keyValues = getKeyValues();
  }
  const refreshInterval = setInterval(
    refreshKeyValues,
    1000
  );
  server.on('close', function onClose() {
    clearInterval(refreshInterval);
  });
}
codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167
  • How is `getKeyValues()` implemented? It's rare to find a CPU intensive task that takes a very long time. Also, your period in the code above is 1 second, not 10. – slebetman Jan 19 '17 at 20:03

2 Answers2

0

The JavaScript's setInterval function is asynchronous, so it not blocks the main flow when it in "waiting" state. But your function refreshKeyValues seems to be not async, so it may block the main JavaScript flow. When it called, the refreshKeyValues can block the flow, because of JavaScript is single threaded. You can take better understanding while reading through this: JavaScript event loop

Community
  • 1
  • 1
Ivan Matveev
  • 225
  • 1
  • 8
0

Ivan Matveev is completely correct. Node.js is single threaded, even though it might look like it is not due to its async nature. However you can achieve what you need with the cluster module. Here is how to do it:

var cluster = require('cluster');


if (cluster.isMaster) {
  var httpWorker = cluster.fork(); // worker thread for server
  var intervalWorker = cluster.fork();  // worker thread for setInterval
  // send messages to your wokers specifying the worker type
  httpWorker.send({ server: true });
  intervalWorker.send({ server: false });
} else {
  process.on('message', function (data) {
    if (data.server) {
      // start server
      var server = require('http').createServer(function (req, res) {
        res.end('OK');
      });
      server.listen(8080, function () {
        console.log('server running');
      });
    } else {
      // start your interval
      setInterval(function () {
            console.log('1s passed');
      }, 1000);
    }
  });
}

EDIT:

Also why are you running your refreshKeyValues function once every second if it takes 10s to run? I would recommend you call it every 10s...

mkhanoyan
  • 1,958
  • 18
  • 15