Skip to content

Instantly share code, notes, and snippets.

@Kevin-Bronsdijk
Last active June 17, 2022 12:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kevin-Bronsdijk/dde6df58f429764a60f7815dd0052adf to your computer and use it in GitHub Desktop.
Save Kevin-Bronsdijk/dde6df58f429764a60f7815dd0052adf to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Net;
using Polly;
using RestSharp;
public static void Run(TimerInfo myTimer, TraceWriter log)
{
int[] httpStatusCodesWorthRetrying = {408, 500, 502, 503, 504};
log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
// Create a retry/exception policy;
// Retry 3 times, calculate the duration to wait
var policy = Policy.Handle<Exception>().WaitAndRetry(3,
attempt => TimeSpan.FromSeconds(0.1 * Math.Pow(2, attempt)),
(exception, calculatedWaitDuration) =>
{
log.Info($"exception: {exception.Message}");
});
try
{
policy.Execute(() =>
{
// Call a Webservice
var client = new RestClient("http://devslice.net/blahblah");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
// Force a retry
if (httpStatusCodesWorthRetrying.Contains((int)response.StatusCode))
throw new Exception("http request failed");
// Handle result
log.Info($" result: {response.StatusCode}");
});
}
catch (Exception e)
{
// Can't recover at this point
log.Info($"critical error: {e.Message}");
}
}
{
"frameworks": {
"net46":{
"dependencies": {
"Polly": "4.3.0",
"RestSharp" : "105.2.3"
}
}
}
}
@dougvdotcom
Copy link

Very helpful, Kevin, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment