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:
1 2 3 | var err = SendtoNetwork.Send(); retry = new Retry(err); retry.now(); |
var err = SendtoNetwork.Send(); retry = new Retry(err); retry.now();
Lets define a payload to invoke the network call with:
1 2 3 4 | class Payload { // adding other parameters string data; }; |
class Payload { // adding other parameters string data; };
We can have a retry policy to specify the max Retries, time between retries etc.
1 2 3 4 5 6 7 8 9 | class RetryPolicy { int maxRetries; int timeBetweenRetries; public RetryPolicy WithMaxRetries(int m) { this->maxRetries = m; return this; } }; |
class RetryPolicy { int maxRetries; int timeBetweenRetries; public RetryPolicy WithMaxRetries(int m) { this->maxRetries = m; return this; } };
Let’s define a function call signature
1 | typedef function<void(Payload)> FUNC; |
typedef function<void(Payload)> FUNC;
Then in the Retry class, we pass in the payload, the function, the retry policy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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; } |
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) —
GD Star Rating
loading...
302 wordsloading...
Last Post: Teaching Kids Programming - Using GroupBy Algorithm to Compress String
Next Post: Teaching Kids Programming - Implement the Accumulate Function in Python