现在的位置: 首页 > 综合 > 正文

IOS GCD Timer

2018年05月11日 ⁄ 综合 ⁄ 共 1799字 ⁄ 字号 评论关闭

使用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被释放了。


抱歉!评论已关闭.