NSTimer callback on background thread

前端 未结 2 1504
夕颜
夕颜 2021-01-23 22:07

I have a NSTimer defined as follows:

timer = [NSTimer scheduledTimerWithTimeInterval:30
                                         target:self
                


        
2条回答
  •  深忆病人
    2021-01-23 22:27

    If you want to run a timer on a background thread, the most efficient way to do that is with a dispatch timer:

    @property (nonatomic, strong) dispatch_source_t timer;
    

    and you can then configure this timer to fire every two seconds:

    - (void)startTimer {
        dispatch_queue_t queue = dispatch_queue_create("com.domain.app.timer", 0);
        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), 2.0 * NSEC_PER_SEC, 0.1 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(self.timer, ^{
            // call whatever you want here
        });
        dispatch_resume(self.timer);
    }
    
    - (void)stopTimer {
        dispatch_cancel(self.timer);
        self.timer = nil;
    }
    

提交回复
热议问题