dispatch_source_t定时器

定时器简述

在iOS中,计时器是比较常用的,用于统计累加数据或者倒计时等,计时器大概有那么三种,分别是:

    NSTimer
    CADisplayLink
    dispatch_source_t

比较

1、NSTimer特性:

  • 存在延迟,不管是一次性的还是周期性的timer的实际触发事件的时间,都会与所加入的RunLoop和RunLoop Mode有关,如果此RunLoop正在执行一个连续性的运算,timer就会被延时出发。重复性的timer遇到这种情况,如果延迟超过了一个周期,则会在延时结束后立刻执行,并按照之前指定的周期继续执行。
  • 必须加入Runloop,使用scheduledTimerWithTimeInterval创建,会自动把timer加入MainRunloop的NSDefaultRunLoopMode中。如果使用以下方式创建定时器,就必须手动加入Runloop:
NSTimer *timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
  • 滑动时停止计时

image.png

如果选择的mode是default的话,当滑动scrollView的时候,定时器是会停止的,你可以将mode设置为common。

2、CADisplayLink特性

特性:

  • 屏幕刷新时调用CADisplayLink是一个能让我们以和屏幕刷新率同步的频率将特定的内容画到屏幕上的定时器类。CADisplayLink以特定模式注册到runloop后,每当屏幕显示内容刷新结束的时候,runloop就会向CADisplayLink指定的target发送一次指定的selector消息, CADisplayLink类对应的selector就会被调用一次。所以通常情况下,按照iOS设备屏幕的刷新率60次/秒
  • 延迟iOS设备的屏幕刷新频率是固定的,CADisplayLink在正常情况下会在每次刷新结束都被调用,精确度相当高。但如果调用的方法比较耗时,超过了屏幕刷新周期,就会导致跳过若干次回调调用机会。如果CPU过于繁忙,无法保证屏幕60次/秒的刷新率,就会导致跳过若干次调用回调方法的机会,跳过次数取决CPU的忙碌程度。

使用场景:
从原理上可以看出,CADisplayLink适合做界面的不停重绘,比如视频播放的时候需要不停地获取下一帧用于界面渲染。

3、dispatch_source_t特性

优点:

  • 时间准确
  • 可以使用子线程,解决定时间跑在主线程上卡UI问题

对比

  • NSTimer会受到主线程的任务的影响,CADisplayLink会受到CPU负载的影响,产生延迟!!
  • dispatch_source_t可以使用子线程,而且使用leeway参数指定可以接受的误差来降低资源消耗!

dispatch_source_t使用实例

dispatch_source_t是可以重复利用的,当我们在一个页面上,需要多次用到时钟的话,可以将dispatch_source_t保存为属性,避免提前释放,然后循环挂起和恢复,就可以达到多次利用的效果:

@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, assign) BOOL isSuspend; //定时器挂起状态

isSuspend记录下挂起的状态,因为dispatch_source_t的suspend和resume要依次进行,不然会crash,而且必须在resume的状态下,才能执行cancel,不然也会crash!!isSuspend默认为YES,因为首次需要resume以启动定时器!

- (dispatch_source_t)timer
{
    if (!_timer) {
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
        uint64_t interval = (uint64_t)(XYHeyMediaPhotoTimerInterval * NSEC_PER_SEC);
        dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, interval, 0);
        @weakify(self);
        dispatch_source_set_event_handler(_timer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                @strongify(self);
                [self updatePhotoProgress];
            });
        });
    }
    return _timer;
}

创建定时器,设置线程,启动时间,时间间隔,以及执行block,如果只执行一次,在block中调用cancel即可,我们这里默认为repeat!

- (void)resumeTimer
{
    if (self.isSuspend) {
        dispatch_resume(self.timer);
        self.isSuspend = NO;
    }
}

在需要启动时钟的时候调用上述方法resumeTimer,只有在已挂起的状态才能执行成功,同理,挂起操作:

- (void)suspendTimer
{
    if (!self.isSuspend) {
        dispatch_suspend(self.timer);
        self.isSuspend = YES;
    }
}

利用resumeTimer和suspendTimer,就可以重复利用该定时器了!!
当我页面销毁的时候,要主动将定时器销毁掉:

- (void)dealloc
{
    if (_timer) {
        if (_isSuspend) {
            dispatch_resume(_timer);
        }
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

代码示例应用:

__block int count= 60;

        [self.sendCodeBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];

        [self.sendCodeBtn setTitle:[NSString stringWithFormat:@"%d s",count] forState:UIControlStateNormal];

        //定时器开始执行的延时时间

        NSTimeInterval delayTime = 1.0f;

        //定时器的间隔时间

        NSTimeInterval timeInterval = 1.0f;

        //创建子线程队列

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

        //使用之前创建的队列来创建计时器

        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

        //设置延时的执行时间,delayTime为要延时的秒数

        dispatch_time_t startDelayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime*NSEC_PER_SEC));

        //设置计时器

        dispatch_source_set_timer(self.timer, startDelayTime, timeInterval*NSEC_PER_SEC, 0.1*NSEC_PER_SEC);

       

        dispatch_source_set_event_handler(self.timer, ^{

        //执行事件

            /**

             * 回主线程更新UI

             */

   

            count--;

    

            dispatch_async(dispatch_get_main_queue(), ^{

            if (count==0) {

            dispatch_cancel(self.timer);//取消定时器

            self.timer = nil;

            self.sendCodeBtn.enabled = YES;

            [self.sendCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];

             [self.sendCodeBtn setTitleColor:[UIColor colorWithRed:254/255. green:218/255. blue:92/255. alpha:1] forState:UIControlStateNormal];

            }

        else{

            self.sendCodeBtn.enabled = NO;

            [self.sendCodeBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];

            [self.sendCodeBtn setTitle:[NSString stringWithFormat:@"%d s",count] forState:UIControlStateNormal];

             }

            });

        });

        //启动计时器

        dispatch_resume(_timer);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值