metal_jacke1
metal_jacke1

Reputation: 416

Executing code only on a Master process in a clustered NodeJS application

The Basics:

I need to trigger an Interval function that calls a third party api endpoint only once per hour. I do not want this function spawned in my workers seeing as this function would get called by each worker per hour.

I see this in a lot of examples:

//Example Clustering
   if (cluster.isMaster) {  

   //Do I insert my function here?

   for (var i = 0; i < numCPUs; i++) {
    // Create a worker
    cluster.fork();
   }

} 
   else {
   var app = express();

   app.get('/', function (req, res) {
    res.send('Hello World!');
   });


   app.listen(8080);
}

I dont know where to place my Timed Nodejs method where it would only be handled by the master process.

Seems like there isn't much guides or tutorials covering this particular topic. Any help greatly appreciated.

Upvotes: 0

Views: 611

Answers (1)

Justas Brazauskas
Justas Brazauskas

Reputation: 321

Yes, you're basically correct - assuming you define makeHttpRequest above, here's how the code might look like:

if (cluster.isMaster) {  
   setInterval(
     () => makeHttpRequest(),
     1000 * 60 * 60
   )

   for (var i = 0; i < numCPUs; i++) {
    // Create a worker
    cluster.fork();
   }

} else {
   var app = express();

   app.get('/', function (req, res) {
    res.send('Hello World!');
   });

   app.listen(8080);
}

Please keep in mind that setInterval is not reliable over short or long timespans, and there are better tools to use. If you need long intervals (e.g. 1 hour), you could use https://github.com/kelektiv/node-cron

Upvotes: 1

Related Questions