Skip to content

Instantly share code, notes, and snippets.

@ritasker
Created September 24, 2018 20:50
Show Gist options
  • Save ritasker/9179d1d526f05bb0b32ef90cc2215d97 to your computer and use it in GitHub Desktop.
Save ritasker/9179d1d526f05bb0b32ef90cc2215d97 to your computer and use it in GitHub Desktop.
Demonstrates How An Exponential Back-Off Works
using System;
using System.Collections.Generic;
public class Program
{
private static int _highInterval;
private static int _lowInterval;
private static int _maxInterval;
private static int _minInterval;
private static int _retryLimit;
public static void Main()
{
_retryLimit = 10;
_minInterval = TimeSpan.Zero.Milliseconds;
_maxInterval = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;
var intervalDelta = (int)TimeSpan.FromMilliseconds(50).TotalMilliseconds;
_lowInterval = (int)(intervalDelta * 0.8);
_highInterval = (int)(intervalDelta * 1.2);
Console.WriteLine($"Exponential (limit {_retryLimit}, min {_minInterval}ms, max {_maxInterval}ms, min delta {_lowInterval}ms, max delta {_highInterval}ms");
var intervals = GetIntervals();
foreach (var i in intervals )
{
Console.WriteLine(i);
}
}
private static IEnumerable<TimeSpan> GetIntervals()
{
var random = GetRandom();
for (var i = 0; _retryLimit == int.MaxValue || i < _retryLimit; i++)
{
var delta = (int)Math.Min(_minInterval + Math.Pow(2, i) * random.Next(_lowInterval, _highInterval), _maxInterval);
yield return TimeSpan.FromMilliseconds(delta);
}
}
private static Random GetRandom()
{
var seed = new Random();
return new Random(seed.Next(int.MinValue,int.MaxValue));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment