ios5nstimernsthread

Difference in scheduling NSTimer in main thread and background thread?


When I call scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: on the main thread and set time interval to 5 seconds code below timer gets executed, and after 5 seconds timer selector is called.

But if I try same in some background thread, the code below scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: will not be executed, it will wait for the timer to fire and then gets executed. Of course, in order to run the timer in the background thread, I first got an instance of NSRunLoop and run it.

Is there a way to set the timer in the background thread and make it non-blocking, so code after it gets executed immediately?


Solution

  • NSTimer requires an active run loop, when initialized in Main Thread it automatically uses the main run loop. If you need to make a background timer you need attach it to the thread’s run loop and invoke run() to make it active.

    1. NSTimer needs one live NSRunLoop to execute it’s events. In main thread, the NSRunLoop is always live and will never stop until the app is terminated, but in other threads, you must invoke run() to active the NSRunLoop.

    2. NSTimer must invoke invalidate() to release the current timer, otherwise, the timer will retain a strong reference of the current instance of target, and it will remain in memory until invalidate() invoked or app terminated;

    3. NSTimer must created and invalidated in the same thread, and a lot of times, we may forget that.

    Take a look at this example , it may be helpful >> http://www.acttos.org/2016/08/NSTimer-and-GCD-Timer-in-iOS/ and the documentation : https://developer.apple.com/documentation/foundation/nstimer