iOS的定时器用法

    定时器在项目中还是经常用到的,很多情况下为了省事我们都是在主线程中直接用,但这样经常会造成阻塞,影响定时器的准确性,对时间精度要求比较高的地方还会给人很不好的体验,比如卡顿等等,所以,定时器的使用最好放在子线程中,下面就记录几种定时器的用法:

1、NSThread

  NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
  [thread start];
    
 - (void)newThread{
    @autoreleasepool{
        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(requestMessages) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] run];
        }
}

2、GCD

首先定义timer:

184953_JBFH_2461772.png

    这里有一点疑惑:timer若作为成员变量(定义放在@interface里面)定时器可以正常使用,但是在方法里面再去定义的定义的话定时器就完全不起作用了,还请知道的原因的小伙伴多多指教:

NSTimeInterval period = 60.0; //设置时间间隔
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timers, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0);
    
    dispatch_source_set_event_handler(_timers, ^{
        //在这里执行事件
        kDLOG(@"定时时间到");
        [self requestMessages];
    });
    
    dispatch_resume(_timers);

GCD的形式有很多种,下面再列举两种:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    uint64_t interval = (uint64_t)(10.0 * NSEC_PER_SEC);
    dispatch_source_set_timer(_timers, start, interval, 0);
    // 设置回调
    dispatch_source_set_event_handler(_timers, ^{
        kDLOG(@"多线程定时时间到");
        [self requestMessages];
    });
    // 启动定时器
    dispatch_resume(_timers);

uint64_t interval = 3 * NSEC_PER_SEC;
    dispatch_queue_t queue = dispatch_queue_create("my queue", 0);
    _timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timers, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);
    
    dispatch_source_set_event_handler(_timers, ^(){
        kDLOG(@"定时时间到");
         });
    dispatch_resume(_timers);


转载于:https://my.oschina.net/u/2461772/blog/636033

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值