Alen Alexander
Alen Alexander

Reputation: 735

NSTimer-Control flow

When I use NSTimer to call a function on certain time interval as follows:

NSTimer *myTimer =[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(func1) userInfo:nil repeats:YES];

does a background thread gets invoked so as to handle the timer to call func1 every 2 minutes ?

How does the program control flows before & after the NSTimer code section? Does these code segments run on main thread ?

Upvotes: 1

Views: 55

Answers (3)

Graham Perks
Graham Perks

Reputation: 23398

The timer's attached to what's called a run loop. The run loop basically controls a thread's operations (in this case, the main thread). It sleeps the thread until awoken by some sort of trigger, e.g. user input, a timer going off, a system message. Once triggered it dispatches the triggering event to the appropriate place, in this case it will invoke your 'func1'. Once func1 returns back to the run loop, it will look for any other input/triggers, and if there are none, sleeps the thread again.

Upvotes: 1

Abhinav
Abhinav

Reputation: 38162

NSTimers are scheduled on the current thread's run loop. So, whichever thread you call the timer on, callback would happen on that thread only.

For instance, below code fires timer of main thread and ensures func1 is called on main thread.

NSTimer *myTimer =[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(func1) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];

You can utilize NSOperation to enable timer & call back on background thread. You need to schedule the timer on [NSRunLoop currentRunLoop]. Of-course GCD is another alternative for timers.

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122458

The timer will be called on the main thread (or whatever thread the timer is scheduled on) and this functionality is handled by the run loop.

You can test this with:

- (void)func1
{
    NSLog(@"Ping! On main thread=%@", [NSThread isMainThread] ? @"Yes" : @"No");
}

Upvotes: 1

Related Questions