Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Timer loop that executes a certain action every X minutes

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?

like image 883
Oscar Avatar asked Oct 20 '25 23:10

Oscar


1 Answers

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.. :)

like image 100
Rashad Avatar answered Oct 22 '25 13:10

Rashad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!