loopbackjs - Node.js periodic tasks with clustering -
i'm running strongloop's loopback api server in production mode. means master process creates many workers, how many cores cpu has. master process controls workers , never execute code.
my purpose execute periodic task once @ time, because runs on 4 workers.
is there suggestions, except cron or 'key lock' in redis-like storage?
in iojs , node v0.12 possible exclusive socket binding. used form of locking similar filesystem based approach. method same both:
attempt exclusive access resource if success: perform task else: not perform task
with sockets this:
net.createserver().on('error', function(err) { console.log('did not lock', err); }).listen({ port: 4321, exclusive: true }, function() { singleprocesstask(); this.close(); });
note exclusive: true
required cluster mode because defaults sharing sockets.
similarly fs.open:
fs.open('lock.file', 'wx', function(err, fd) { if (err) { console.log('did not lock', err); } else{ singleprocesstask(); fs.close(fd, function(err) { // insert error handling here fs.unlink('lock.file', function(err) { // insert error handling here }); }); });
in both cases there potential race conditions if task quick , processes on different timer schedules. in these cases task still performed 1 process @ time, may processed multiple times per scheduled period depending on how implement scheduling.
edit: more illustrative example
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 lock', err); }).listen({ host: '127.0.0.1', port: 4321, exclusive: true }, function() { fn(); this.close(); }); }
Comments
Post a Comment