Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatch_after looped / repeated

I am trying to create a loop like this:

while (TRUE){
  dispatch_after(...{
    <some action>
  });
}

After a viewDidLoad. The idea is to repeat the dispatch_after repeatedly. The dispatch_after waits two seconds before doing the action.

This does not work - the screen just blanks? Is it stuck in looping or ...?

like image 742
Roel Van de Paar Avatar asked Nov 28 '22 02:11

Roel Van de Paar


1 Answers

Yes, you can do that with gcd. You need two additional c-functions though.

static void dispatch_async_repeated_internal(dispatch_time_t firstPopTime, double intervalInSeconds, dispatch_queue_t queue, void(^work)(BOOL *stop)) {    
    __block BOOL shouldStop = NO;
    dispatch_time_t nextPopTime = dispatch_time(firstPopTime, (int64_t)(intervalInSeconds * NSEC_PER_SEC));
    dispatch_after(nextPopTime, queue, ^{
        work(&shouldStop);
        if(!shouldStop) {
            dispatch_async_repeated_internal(nextPopTime, intervalInSeconds, queue, work);
        }
    });
}

void dispatch_async_repeated(double 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);
}

Tested! Works as intended.

https://gist.github.com/4676773

like image 93
hfossli Avatar answered Dec 05 '22 09:12

hfossli