Last active
April 3, 2019 13:37
-
-
Save giuliohome/088da80d3f82e5cb9570791ea627268e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//usage: | |
//TimeIt(() => Extract(sql_trades, "03_Trade_Valid_" + timestamp + ".csv"), "Trade Extract"); | |
static bool Retry(int count, Action action, Action<int> startCallback, Func<Exception, int, bool> exceptionCallback) | |
{ | |
if (count <= 0) { return false; } else | |
{ | |
try | |
{ | |
startCallback(count); | |
action(); | |
return true; | |
} | |
catch (Exception exc) | |
{ | |
if (!exceptionCallback(exc, count) || count <= 0) { return false; } | |
else | |
{ | |
return Retry(count - 1, action, startCallback, exceptionCallback); //with tail recursion but C# does not emit tail. prefix | |
} | |
} | |
} | |
} | |
static void StartCallback(int curr_count, int startCount = 10, int millisecons = 15000) | |
{ | |
if (curr_count < startCount) | |
{ | |
Thread.Sleep(millisecons); | |
} | |
} | |
static bool ExceptionCallback(string actionName, string message, Exception exc, int curr_count) | |
{ | |
if (!exc.Message.Contains(message)) | |
{ | |
Console.WriteLine(actionName + ", quitting due to error: " + exc.Message); | |
return false; | |
} | |
Console.WriteLine(actionName + ", retry countdown #" + curr_count + ": " + exc.Message); | |
return true; | |
} | |
static void TimeIt(Action action, string actionName, int count = 10, string excMessage = "The command has timed out", int millisecons = 60000) | |
{ | |
Stopwatch clock = new Stopwatch(); | |
clock.Start(); | |
bool success = Retry(count, action, curr_count => | |
StartCallback(curr_count, count, millisecons), (exc, curr_count) => ExceptionCallback(actionName, excMessage, exc, curr_count)); | |
clock.Stop(); | |
Console.WriteLine(actionName + " " + (success?"succesful":"failed") + " after " + clock.Elapsed.TotalSeconds.ToString("0.0") + " seconds"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment