-
Notifications
You must be signed in to change notification settings - Fork 2
/
heartbeat.js
48 lines (38 loc) · 1.05 KB
/
heartbeat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Core File When Heartbeat is Required (recommended) //
var fork = require('child_process').fork;
var server, heartbeat;
function startServer() {
console.log('Starting server with Heartbeat');
server = fork('app.js');
//when the server goes down restart it
server.on('close', (code) => {
startServer();
});
//when server sends a heartbeat message save it
server.on('message', (message) => {
heartbeat = message ? message.heartbeat : null;
});
//ask the server for a heartbeat
server.send({
request: 'heartbeat'
});
//wait 5 seconds and check if the server responded
setTimeout(checkHeartbeat, 5000);
}
function checkHeartbeat() {
if (heartbeat) {
// console.log('Server is alive');
//clear the heart beat and send request for a new one
heartbeat = null;
server.send({
request: 'heartbeat'
});
//set another hearbeat check
setTimeout(checkHeartbeat, 5000);
} else {
console.log('Server looks stuck...killing');
server.kill();
setTimeout(startServer(), 2000);
}
}
startServer();