Search code examples
node.jsmultithreadingcronnode-cluster

Nodejs cluster assign task only to one worker(Any)


The problem I am facing is that the project has already programmed with cluster to distribute task.

if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
  cluster.on('exit', (worker, code, signal) => {
  });
} else {
var server = http.createServer(app);
var usernames = {};
var showusernames = {};
var usersmessages = [];
require('../server/controllers/communication/chat.js').chatConfig(io, usernames);
    /**
     * Listen on provided port, on all network interfaces.
     */
    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);
    }

I have a basic idea that this code is for distributing task among cpu and keeping server live in case one cpu fails.

The question is: Everything was working fine till I need started working with node to schedule the cron job (which will be send email). The cron now is ran by all workers simultaneously and the email is send to worker depending on how many cpu are there on server. The I worker my way out by scheduling job as:

 if(cluster.isWorker)
 if(cluster.worker.id == 1){
   cron.schedule('*/1 * * * *', function() {
     //CRON JOB
 })
 } 

This worked very fine within local system but failed in staging server maybe because of CPU aligned to this very project.

Is there any way to get only the first free worker and assign task to him.

Now i tried this

var wokerArr = []
wokerArr.push(cluster.worker.id)
if(cluster.worker.id == wokerArr[0])
cron.schedule('*/1 * * * *', function() {
    //CRON JOB
})

Solution

  • I did that using the crontab. Making a separate cron file and schedule the job using crontab in command prompt to schedule job. Thanks for support.