Skip to content

Instantly share code, notes, and snippets.

@deflexor
Created February 12, 2017 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deflexor/c6d8375dfff97300da2690a6e95465c9 to your computer and use it in GitHub Desktop.
Save deflexor/c6d8375dfff97300da2690a6e95465c9 to your computer and use it in GitHub Desktop.
Write a recursive exponential backoff service (ping) check.
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