Skip to content

Instantly share code, notes, and snippets.

@giuliohome giuliohome/TimeIt.cs
Last active Apr 3, 2019

Embed
What would you like to do?
//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
You can’t perform that action at this time.