GCD實現定時器

GCD學習(二)
async


(1)dispatch source建立定時器函數

//dispatch source定時器
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_queue_t mainq = dispatch_get_main_queue();//主線程
    
    if (source) {
        
        dispatch_source_set_timer(source, dispatch_walltime(DISPATCH_TIME_NOW, 0), 2 * NSEC_PER_SEC, 0);
        
        dispatch_source_set_event_handler(source, ^{
            
            dispatch_async(mainq, ^{
                
                [self testTimerOper];
            });
            
        });
    }
    
    dispatch_resume(source);
    
//用戶執行操做
-(void)testTimerOper {
    
    
    NSLog(@"測試timer執行");
}

上述例子每2秒會執行一次testTimerOper函數;可使用dispatch_source_cancel(source)關閉定時器。學習

注意:dispatch_source_t source 須定義爲全局變量,不然會被釋放致使運行不成功。測試

相關文章
相關標籤/搜索