How to run Cron Job in Node.js application that uses cluster module?

后端 未结 5 1081
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 04:02

I\'m using node-cron module for scheduling tasks in Node.js application. I also want run the application in several processes using core cluster module.

Running applica

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 04:36

    I also have a problem with cluster module and finally i found sample way to solve problem.

    Let master cluster execute cronJob.

    My project use Kue to manage jobs. When cronJob run i get a list of jobs.

    index.js

    global.cluster = require('cluster');
    
    if (cluster.isMaster) {
      const cpuCount = require('os').cpus().length;
      for (let i = 0; i < cpuCount; i += 1) {
        cluster.fork();
      }
    } else {
      // start your express server here
      require('./server')
    }
    
    cluster.on('exit', worker => {
      logger.warn('Worker %d died :(', worker.id);
      cluster.fork();
    });
    

    cron.js

    const cron = require('cron').CronJob;
    
    const job = new cron('* * * * *', async () => {
      if (cluster.isMaster) {
        console.log('cron trigger');
      }
    });
    
    job.start();
    

    Hope this help.

提交回复
热议问题