1

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
})
sndpkpr
  • 589
  • 6
  • 16

2 Answers2

0

You can schedule the cron in master process itself. Cron needs to be handled in an idempotent way.

if (cluster.isMaster) {
  cron.schedule('*/1 * * * *', function() {
     //CRON JOB
  })

  // continue initializing workers here
}
tbking
  • 8,796
  • 2
  • 20
  • 33
  • thank you for the response. I actually figured out something more adequate. To do the cron job separately using `crontab`. But your answer is correct. :) – sndpkpr Dec 22 '17 at 09:08
  • what is there are multiple servers that can be master? – Aryeh Armon Feb 24 '19 at 16:59
0

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.

sndpkpr
  • 589
  • 6
  • 16