I tried to create a retry logic that has a time limit lets say 6 seconds with a retry count of 6 times (including the first try) and if a retry is failed before 1sec , it will sleep for the rest of the second and try the request in the next second only . I don't know if there is a better way to achieve this other than the one below .
What I tried is
public bool RetryFunc(Func<Response,bool> function, DataModel data)
{
int duration=6; //in seconds
int retryCount=5;
bool success = false;
Stopwatch totalRetryDurationWatch = new Stopwatch();// begin request
totalRetryDurationWatch.Start();// first try
success = function(data);
int count = 1;
while (!success && count <= retryCount)
{
Stopwatch thisRetryDurationWatch = new Stopwatch();// Begining of this retry
thisRetryDurationWatch.Start();
success = function(data);//End this retry
thisRetryDurationWatch.Stop();
if (totalRetryDurationWatch.Elapsed.Seconds>=duration)
{
return false;
}
else if (!success) {
// To wait for the second to complete before starting another retry
if (thisRetryDurationWatch.ElapsedMilliseconds < 1000)
System.Threading.Thread.Sleep((int)(1000 - thisRetryDurationWatch.ElapsedMilliseconds));
}
count++;
}
totalRetryDurationWatch.Stop();//To end the retry time duration watch
return success;
}
Any help is much appreciated , Thanks .