Question

I am trying to execute a certain block of code every x amount of time, but it seems that all I am doing is executing it during that time. Here's a block of my code.

while (TRUE) {
    NSTimer *countDown = [NSTimer
                       scheduledTimerWithTimeInterval:(x)
                       target:self
                       selector:@selector(timerHandle)
                       userInfo:nil
                       repeats:YES];

}

Any ideas as to how to do it?

Was it helpful?

Solution

As written, this is an infinite loop, creating an NSTimer every loop iteration.

Try it without the while loop. This should cause [self timerHandle] to be invoked on interval x by a single background thread/timer. The Apple guide to NSTimer usage (including as others point out, how to properly stop your timed task) is here.

OTHER TIPS

Try this: (It will call executeMethod on every 5 sec)

if (![NSThread isMainThread]) {

    dispatch_async(dispatch_get_main_queue(), ^{
        [NSTimer scheduledTimerWithTimeInterval:5.0
                                         target:self
                                       selector:@selector(executeMethod)
                                       userInfo:nil
                                        repeats:YES];
    });
}
else{
    [NSTimer scheduledTimerWithTimeInterval:5.0
                                     target:self
                                   selector:@selector(executeMethod)
                                   userInfo:nil
                                    repeats:YES];
}

Write the code you want to be executed in executeMethod method. Hope this helps.. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top