Created
April 22, 2011 08:39
-
-
Save takekazuomi/936282 to your computer and use it in GitHub Desktop.
retry code
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
namespace Jobs { | |
public static class Retry { | |
static ILog log = LogManager.GetCurrentClassLogger(); | |
public static RetryPolicy Exponential(int retryCount, TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan deltaBackoff) { | |
// Do any argument Pre-validation here, i.e. enforce max retry count etc. | |
return () => { | |
return (int currentRetryCount, Exception lastException, out TimeSpan retryInterval) => { | |
log.Info(m => m("currentRetryCount:{0},lastException:{1}", currentRetryCount, lastException)); | |
if (currentRetryCount < retryCount) { | |
Random r = new Random(); | |
// Calculate Exponential backoff with +/- 20% tolerance | |
int increment = (int)((Math.Pow(2, currentRetryCount) - 1) * r.Next((int)(deltaBackoff.TotalMilliseconds * 0.8), (int)(deltaBackoff.TotalMilliseconds * 1.2))); | |
// Enforce backoff boundaries | |
int timeToSleepMsec = (int)Math.Min(minBackoff.TotalMilliseconds + increment, maxBackoff.TotalMilliseconds); | |
retryInterval = TimeSpan.FromMilliseconds(timeToSleepMsec); | |
return true; | |
} | |
retryInterval = TimeSpan.Zero; | |
return false; | |
}; | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment