Created
February 12, 2017 22:47
-
-
Save deflexor/c6d8375dfff97300da2690a6e95465c9 to your computer and use it in GitHub Desktop.
Write a recursive exponential backoff service (ping) check.
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 http = require('http'); | |
const RetryIntervals = [500, 1000, 4000]; | |
const retryTries = 4; | |
function pingService(retryInterval, retryTry) { | |
if(retryTry >= retryTries) { | |
console.log(`ping not ok after ${retryTries} retries, giving up.`); | |
return; | |
} | |
const opts = { | |
host: 'sample.com', | |
path: '/zzz' | |
}; | |
const retry = function(retryInterval) { | |
console.log(`retry after ${RetryIntervals[retryInterval]} seconds...`); | |
setTimeout(function() { | |
const newRetry = (retryInterval + 1 < RetryIntervals.length) ? retryInterval + 1 : retryInterval; | |
pingService(newRetry, retryTry+1); | |
}, RetryIntervals[retryInterval]); | |
}; | |
const req = http.request(opts, (res) => { | |
if(res.statusCode === 200) { | |
console.log('ping ok!'); | |
} | |
else { | |
console.log('ping not ok!'); | |
retry(retryInterval); | |
} | |
}); | |
req.on('error', (e) => { | |
console.log(`problem with request: ${e.message}`); | |
retry(retryInterval); | |
}); | |
req.end(); | |
} | |
pingService(0, 0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment