Timer in another thread in Objective - C

I need to define a method that should be called periodically with some time interval. I need to call it in another thread (NOT the main thread), because this method is used to get information from an external API and synchronize data in the main data.

How to define this method so as not to block the main thread?

+8
ios objective-c nstimer nsrunloop nsblockoperation
source share
2 answers

Unless you have a special need for timers, you can use Grand Central Dispatch.

The next fragment will execute the block after 2 seconds in a parallel default priority queue (i.e. background thread). You can change the priority of the queue if you think it is necessary, but if you do not deal with many different operations in parallel queues, by default it will be enough.

double delayInSeconds = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ // Your code here }); 

If you want to call it repeatedly, you can use dispatch_source_set_timer to set repetitive execution. The essence of this is below:

 // Create a dispatch source that'll act as a timer on the concurrent queue // You'll need to store this somewhere so you can suspend and remove it later on dispatch_source_t dispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); // Setup params for creation of a recurring timer double interval = 2.0; dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, 0); uint64_t intervalTime = (int64_t)(interval * NSEC_PER_SEC); dispatch_source_set_timer(dispatchSource, startTime, intervalTime, 0); // Attach the block you want to run on the timer fire dispatch_source_set_event_handler(dispatchSource, ^{ // Your code here }); // Start the timer dispatch_resume(dispatchSource); // ---- // When you want to stop the timer, you need to suspend the source dispatch_suspend(dispatchSource); // If on iOS5 and/or using MRC, you'll need to release the source too dispatch_release(dispatchSource); 
+13
source share

Use NSRunLoop and NSTimer to work

 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer) userInfo:nil repeats:NO]; [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; 
+1
source share

All Articles