1. 程式人生 > >GCD dispatch_source基本使用,創建GCD定時器與NSTimer的區別

GCD dispatch_source基本使用,創建GCD定時器與NSTimer的區別

pre 任務調度 cnblogs class -s ping log glob ...

可以使用GCD創建定時器

創建定時器:

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    self.timer = timer;
    
    // 定時任務調度設置,4秒後啟動,每個5秒運行
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW , 4);
    dispatch_source_set_timer(self.timer, time, 5 * NSEC_PER_SEC, 3 * NSEC_PER_SEC);
    
    dispatch_source_set_event_handler(self.timer, ^{
        // 定時任務
        NSLog(@"%s",__func__);
    });
    
    dispatch_source_set_cancel_handler(self.timer, ^{
        // 定時取消回調
        NSLog(@"source did cancel...");
    });
    
    // 啟動定時器
    dispatch_resume(timer);

註意創建gcd定時器timer後,需要保存timer,需要有個引用引用timer,要不然timer會銷毀

@property (nonatomic, strong) dispatch_source_t timer;

取消定時器

    dispatch_source_cancel(self.timer);
    self.timer = nil;

總結

GCD定時器

1.時間調度很準確,時間是以納秒為單位,NSTimer更加精確

2.GCD是不受runloop的影響, 比如:拖動scrollView,不會影響GCD定時器的運行

NSTimer定時器

1.時間調度可能會有誤差,時間是以秒為單位,GCD timer精確

2.runloop的影響, 比如:拖動scrollView,會影響定時器的運行

GCD dispatch_source基本使用,創建GCD定時器與NSTimer的區別