Objective-C retry helper with capped exponential backoff
Objective-C
#import <Foundation/Foundation.h>
#import <math.h>
#import <stdlib.h>
static void RetryWithBackoff(NSInteger maxRetries, BOOL (^operation)(NSError **)) {
__block NSInteger attempt = 0;
__block void (^run)(void);
run = ^{
NSError *error = nil;
if (operation(&error) || attempt >= maxRetries) {
if (error) NSLog(@"retry gave up: %@", error.localizedDescription);
return;
}
double delay = MIN(0.25 * pow(2.0, attempt), 8.0);
delay += (double)arc4random_uniform(250) / 1000.0; // jitter below 250 ms
attempt += 1;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)),
dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), run);
};
run();
}