Created
January 20, 2019 02:24
-
-
Save jackhftang/67ce453d66d9cbc1a6ca838ba3ad5e85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cluster = require('cluster'); | |
const minions = ['alpha', 'beta']; | |
const tHeartBeat = 1000 | |
const tCheck = 1000 | |
const tTimeout = 3000 | |
if (cluster.isMaster) { | |
for (let id of minions) cluster.fork({id}); | |
let lastHeartbeat = {} | |
cluster.on('message', (worker, {id}) => { | |
console.log(`receive heartbeat from ${id}`) | |
// record last heartbeat time | |
lastHeartbeat[id] = Date.now(); | |
}) | |
// health check scheduler | |
setInterval(_ => { | |
let now = Date.now() | |
console.log('check', lastHeartbeat) | |
for(let id of minions){ | |
if(lastHeartbeat[id] + tTimeout < now){ | |
console.log(`worker ${id} is dead`) | |
} | |
} | |
}, tCheck) | |
} else { | |
let id = process.env.id | |
console.log(`minion ${id} started`) | |
let startTime = Date.now() | |
setInterval(_ => { | |
if(id !== minions[0] || Date.now() < startTime + 3000) process.send({id}) | |
}, tHeartBeat); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment