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

后端 未结 5 1079
隐瞒了意图╮
隐瞒了意图╮ 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:29

    I actually do not like the redis approach that is also used in the cron-cluster npm plugin, because I do not want to have that redis server running on my maschine and maintain it, too.

    I would like to discuss this approach with you:

    Pro: we do not need to use redis Con: cron jobs are always running on the same worker

    I use the message passing only for this, if you use it for other things, you want to pass the information that

    if (cluster.isMaster) {
        // Count the machine's CPUs
        var cpuCount = require('os').cpus().length;;
    
        // Create a worker for each CPU
        for (var i = 0; i < cpuCount; i += 1) {
            cluster.fork();
        }
    
        cluster.on('fork', (worker) => {
            console.log("cluster forking new worker", worker.id);
        });
    
        // have a mainWorker that does the cron jobs.
        var mainWorkerId = null;
    
        cluster.on('listening', (worker, address) => {
            console.log("cluster listening new worker", worker.id);
            if(null === mainWorkerId) {
                console.log("Making worker " + worker.id + " to main worker");
                mainWorkerId = worker.id;
            worker.send({order: "startCron"});
            }
        });
    
        // Listen for dying workers if the mainWorker dies, make a new mainWorker
        cluster.on('exit', function (worker, code, signal) {
            console.log('Worker %d died :(', worker.id);
    
            if(worker.id === mainWorkerId) {
                console.log("Main Worker is dead...");
                mainWorkerId = null;
            }
    
            console.trace("I am here");
            console.log(worker);
            console.log(code);
            console.log(signal);
            cluster.fork();
    
        });
    // Code to run if we're in a worker process
    } else {
    
        // other code like setup app and stuff
    
        var doCron = function() {
            // setup cron jobs...
        }
    
        // Receive messages from the master process.
        process.on('message', function(msg) {
            console.log('Worker ' + process.pid + ' received message from master.', message);
            if(message.order == "startCron") {
                doCron();
            }
        });
    }
    

提交回复
热议问题