IOS GCD Timer

使用GCD中的dispatch_after来实现单次的延时调用:

?
1
2
3
4
5
double delayInSeconds = 2.0;
     dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
     dispatch_after(popTime, dispatch_get_main_queue(), ^( void ){
         [self someMethod];
     });


GCD中的Timer

GCD中的Timer应该是最灵活的,而且是多线程的。GCD中的Timer是靠Dispatch Source来实现的。

因此先需要声明一个dispatch_source_t本地变量:

@interface ViewController ()

{

    dispatch_source_t _timer;

}

 

接着通过dispatch_source_create函数来创建一个专门的Dispatch Source,接着通过dispatch_source_set_timer函数来设置Timer的参数,注意这里的时间参数有些蛋疼。

开始时间的类型是dispatch_time_t,最好用dispatch_time或者dispatch_walltime函数来创建dispatch_time_t对象。如果需要Timer立即执行,可以传入dispatch_time(DISPATCH_TIME_NOW, 0)。

internal和leeway参数分别表示Timer的间隔时间和精度。类型都是uint64_t。间隔时间的单位竟然是纳秒。可以借助预定义的NSEC_PER_SEC宏,比如如果间隔时间是两秒的话,那interval参数就是:2 * NSEC_PER_SEC。

leeway就是精度参数,代表系统可以延时的时间间隔,最高精度当然就传0。

然后通过dispatch_source_set_event_handler函数来设置Dispatch Source的事件回调,这里当然是使用Block了。

最后所有dispatch_source_t创建后默认都是暂停状态的,所以必须通过dispatch_resume函数来开始事件监听。这里就代表着开始Timer。

完整代码:

NSLog(@"主线程 %@", [NSThread currentThread]);

//间隔还是2

uint64_t interval = 2 * NSEC_PER_SEC;

//创建一个专门执行timer回调的GCD队列

dispatch_queue_t queue = dispatch_queue_create("my queue"0);

//创建Timer

_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER00, queue);

//使用dispatch_source_set_timer函数设置timer参数

dispatch_source_set_timer(_timerdispatch_time(DISPATCH_TIME_NOW0), interval, 0);

//设置回调

dispatch_source_set_event_handler(_timer, ^()

{

    NSLog(@"Timer %@", [NSThread currentThread]);

});

//dispatch_source默认是Suspended状态,通过dispatch_resume函数开始它

dispatch_resume(_timer);

 

输出:

主线程 <NSThread: 0x711fab0>{name = (null), num = 1}

Timer <NSThread: 0x713a380>{name = (null), num = 3}

Timer <NSThread: 0x713a380>{name = (null), num = 3}

Timer <NSThread: 0x713a380>{name = (null), num = 3}


转自:http://www.th7.cn/Program/IOS/201308/147219.shtml

备注:如果发现所调用的方法只调用了几次后不再调用,可能是timer被释放了。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值