Cron Job在Node js中的集群环境下多次运行

时间:2018-06-24 07:38:23

标签: node.js npm cron node-cluster

我已经设置了Node JS服务器集群环境,以充分利用服务器的所有核心。有一个Cron Job,每天08点运行,以运行一些任务。但是由于群集,它每天在08点运行4次(服务器是4个内核)。 我怎么能克服这个问题,每天只运行一次Cron Job?

if(cluster.isMaster) {
    var numWorkers = require('os').cpus().length;

    console.log('Master cluster setting up ' + numWorkers + ' workers...');

    for(var i = 0; i < numWorkers; i++) {
        cluster.fork();
    }

    cluster.on('exit', function(worker, code, signal) {
        console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
        cluster.fork();
    });
} else {

    var CronJob = require('cron').CronJob;
    new CronJob('01 30 08 * * 0-6', function() {
      console.log('Running Schedular');
      //Performing tasks
    }, null, true, 'America/Los_Angeles');

    var server = app.listen(port, function() {
        console.log('Process ' + process.pid + ' is listening to all incoming requests');
    });
}

2 个答案:

答案 0 :(得分:0)

嗨,请找到以下更改,我只是将cron作业更改为if条件。

SELECT 
    Month_year,
    STUFF((SELECT ',' + QUOTENAME(Weeks) 
           FROM MyTestTable 
           GROUP BY Weeks
           ORDER BY Weeks 
           FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM
    (SELECT 
         Month_year, weeks, Xcount
     FROM
         MyTestTable) x
PIVOT
    (SUM(xCount)
        FOR Weeks IN (STUFF((SELECT ',' + QUOTENAME(Weeks) 
                             FROM MyTestTable 
                             GROUP BY Weeks
                             ORDER BY Weeks 
                             FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ''))
    ) p 

答案 1 :(得分:0)

让主群集处理cron作业,而不是其中一个工作线程。