As a user – I want to build a simple retry library, which retries on error and has a mechanism to do an exponential backoff. For example:
var err = SendtoNetwork.Send();
retry = new Retry(err);
retry.now();
Lets define a payload to invoke the network call with:
class Payload {
// adding other parameters
string data;
};
We can have a retry policy to specify the max Retries, time between retries etc.
class RetryPolicy {
int maxRetries;
int timeBetweenRetries;
public RetryPolicy WithMaxRetries(int m) {
this->maxRetries = m;
return this;
}
};
Let’s define a function call signature
typedef function<void(Payload)> FUNC;
Then in the Retry class, we pass in the payload, the function, the retry policy:
class Retry {
public:
Retry(FUNC func, Payload &payload, RetryPolicy retryPolicy):
func(func), maxRetries(maxRetries), payload(payload) {
numOfTries = 0;
}
void now() {
while (numOfTries < maxRetries) {
try {
func(payload);
break;
} catch (std::exception &ex) {
if (numOfTries ++ <= retryPolicy.maxRetries) {
sleep(1 << numOfTries);
} else {
throw std::run_time_exception(ex, "exceeded max retries");
}
}
}
}
private:
FUNC func;
Payload payload;
int numOfTries;
int maxRetries;
}
And in the execute (now) function, we call the function with payload, and if we can still retry – then, we retry otherwise we throw a runtime exception. The first time, it will wait 1 second before next retry, and then wait for 2 seconds, 4 seconds – exponential strategy.
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Teaching Kids Programming - Using GroupBy Algorithm to Compress String
Next Post: Teaching Kids Programming - Implement the Accumulate Function in Python