Skip to content

Instantly share code, notes, and snippets.

@karnlund
Forked from hfossli-agens/gist:4676773
Created June 11, 2015 00:00
Show Gist options
  • Save karnlund/44b16d96effff998ff53 to your computer and use it in GitHub Desktop.
Save karnlund/44b16d96effff998ff53 to your computer and use it in GitHub Desktop.
static void dispatch_async_repeated_internal(dispatch_time_t firstPopTime, NSTimeInterval intervalInSeconds, dispatch_queue_t queue, void(^work)(BOOL *stop))
{
dispatch_after(firstPopTime, queue, ^{
BOOL shouldStop = NO;
work(&shouldStop);
if(!shouldStop)
{
dispatch_time_t nextPopTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(intervalInSeconds * NSEC_PER_SEC));
dispatch_async_repeated_internal(nextPopTime, intervalInSeconds, queue, work);
}
});
}
void dispatch_async_repeated(NSTimeInterval intervalInSeconds, dispatch_queue_t queue, void(^work)(BOOL *stop))
{
dispatch_time_t firstPopTime = dispatch_time(DISPATCH_TIME_NOW, intervalInSeconds * NSEC_PER_SEC);
dispatch_async_repeated_internal(firstPopTime, intervalInSeconds, queue, work);
}
@karnlund
Copy link
Author

There is no need for the __block variable.

And this modification has additional protection against work that takes longer than intervalInSeconds.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment