GCD下 timer

在GCD中,我们不能正常的使用NSTimer了,在子线程中runloop默认是关闭的,我们可以通过食用gcd的timer相关实现:

    // 初始化一个gcd队列.
    dispatch_queue_t timerQueue = dispatch_queue_create("test_timer_queue", 0);

    // 创建 gcd timer.
    dispatch_source_t _timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerQueue);

    double interval = 10 * NSEC_PER_SEC; // 间隔10秒
    dispatch_source_set_timer(_timerSource, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);

    // 定时器block设置
    dispatch_source_set_event_handler(_timerSource, ^{
        // 定时处理代码

    });

    // 唤起定时器任务.
    dispatch_resume(_timerSource);

当然如果非要在子线程中使用NSTimer,经过测试以下代码可以实现,将NSTimer 对象加入到主线程的runloop中:

NSTimer *timer = [NSTimer timerWithTimeInterval:10 target:self selector:@selector(timeOutAction) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

该方法创建一个timer的对象,不把它知道那个到run loop. (当创建之后,你必须手动的调用NSRunLoop下对应的方法 addTimer:forMode: 去将它制定到一个runloop模式中.)

在这里不能使用

- scheduledTimerWithTimeInterval: invocation: repeats:

该方法创建一个timer并把它指定到一个默认的runloop模式中,而子线程的runloop是默认关闭的,所以使用了,是没有效果的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值