Runloop定时器

- (void)createTimerInOtherThread{
    
    //内存分配器 NULL = kCFAllocatorDefault = CFAllocatorGetDefault()
    CFAllocatorRef allocator = kCFAllocatorDefault;
    //定时器开启时间  绝对时间
    CFAbsoluteTime fireDate = CFAbsoluteTimeGetCurrent();
    
    //时间间隔
    CFTimeInterval interval = 1.0;
    CFOptionFlags flags = 0;
    CFIndex order = 0;
    //回调函数
    CFRunLoopTimerCallBack callout = lefexTimerAction;
    
    //定时器上下文
    CFRunLoopTimerContext context = {
        0,
        (__bridge void *)(self),
        NULL,
        NULL,
        NULL
    };
    //获取当前runloop
    threadRunloop = CFRunLoopGetCurrent();
    
    //创建定时器
    timer = CFRunLoopTimerCreate(allocator, fireDate,interval, flags, order, callout , &context);
    //添加到runloop
    CFRunLoopAddTimer(threadRunloop, timer, kCFRunLoopCommonModes);
    //非主线程的runloop需要主动开启,将进入死循环
    CFRunLoopRun();
    
    //当runloop关闭 这里才会执行
    NSLog(@"never excute,if not timer invalid");
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self invalidTimer:timer];
}

//定时器执行回调,回调函数在被添加的runloop对应的线程中执行
void lefexTimerAction(CFRunLoopTimerRef timer, void *info){
    NSLog(@"timer called on thread:%@",[NSThread currentThread]);
}

- (void)invalidTimer:(CFRunLoopTimerRef)timer{
    //释放timer
    if (timer) {
        CFRunLoopTimerInvalidate(timer);
        CFRelease(timer);
        timer = nil;
    }
    //停止Runloop的运行
    if (threadRunloop) {
        CFRunLoopStop(threadRunloop);
        threadRunloop = NULL;
    }
}

你可能感兴趣的:(Runloop定时器)