Node.js周期性任务与集群

我在生产模式下运行StrongLoop的Loopback API服务器。 这意味着主进程会创build尽可能多的工人,你的CPU有多less核心。 因此,主进程只控制工作人员,永远不执行你的代码。

我的目的是当时只执行一次定期任务,因为现在它运行在所有4名工作人员身上。

除了cron或Redis类存储中的“密钥locking”之外,是否有任何build议?

在iojs和node v0.12中,可以做一个独占的套接字绑定 。 这可以用作类似于基于文件系统的方法的lockingforms。 这两种方法是相同的:

attempt exclusive access to resource if success: perform task else: do not perform task 

用套接字,你会做这样的事情:

 net.createServer().on('error', function(err) { console.log('did not get lock', err); }).listen({ port: 4321, exclusive: true }, function() { singleProcessTask(); this.close(); }); 

请注意, exclusive: true仅适用于群集模式,因为它默认为共享套接字。

与fs.open类似:

 fs.open('lock.file', 'wx', function(err, fd) { if (err) { console.log('did not get lock', err); } else{ singleProcessTask(); fs.close(fd, function(err) { // insert error handling here fs.unlink('lock.file', function(err) { // insert error handling here }); }); }); 

在这两种情况下,如果您的任务非常快并且您的stream程稍有不同,则可能会出现竞争状况。 在这些情况下,任务仍然只能由一个进程一次执行,但是可能会在每个预定时间段内处理多次,具体取决于您如何实施调度。

编辑:更多说明性的例子

 var net = require('net'); var HOUR = 60*60*1000; setInterval(myTask, HOUR); function myTask() { locked(function() { // task code here }); } function locked(fn) { net.createServer().on('error', function(err) { console.log('did not get lock', err); }).listen({ host: '127.0.0.1', port: 4321, exclusive: true }, function() { fn(); this.close(); }); } 
Interesting Posts