美文网首页
iOS 中的定时器

iOS 中的定时器

作者: 老猫_2017 | 来源:发表于2020-01-10 11:30 被阅读0次

定时器常用来做一些定时任务,iOS定时 实现有如下

NSTimer,0.1s 误差 50-100 milliseconds.
dispatch_source_set_timer,
CADisplayLink 每秒 60 帧,间隔 16.67 ms
dispatch_after
performSelector() after
mach_timebase_info_data_t 最高精度,可以达到 nano妙

swift dispatch timer

/// RepeatingTimer mimics the API of DispatchSourceTimer but in a way that prevents
/// crashes that occur from calling resume multiple times on a timer that is
/// already resumed (noted by https://github.com/SiftScience/sift-ios/issues/52
class RepeatingTimer {

    let timeInterval: TimeInterval
    
    init(timeInterval: TimeInterval) {
        self.timeInterval = timeInterval
    }
    
    private lazy var timer: DispatchSourceTimer = {
        let t = DispatchSource.makeTimerSource()
        t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval)
        t.setEventHandler(handler: { [weak self] in
            self?.eventHandler?()
        })
        return t
    }()

    var eventHandler: (() -> Void)?

    private enum State {
        case suspended
        case resumed
    }

    private var state: State = .suspended

    deinit {
        timer.setEventHandler {}
        timer.cancel()
        /*
         If the timer is suspended, calling cancel without resuming
         triggers a crash. This is documented here https://forums.developer.apple.com/thread/15902
         */
        resume()
        eventHandler = nil
    }

    func resume() {
        if state == .resumed {
            return
        }
        state = .resumed
        timer.resume()
    }

    func suspend() {
        if state == .suspended {
            return
        }
        state = .suspended
        timer.suspend()
    }
}

相关文章

  • iOS进阶-谈谈定时器

    目录 iOS提供定时器API 定时器开发中的坑 一、 iOS提供定时器API 二、定时器开发中的坑 2.1、必须办...

  • iOS中的定时器

    点击这里>> cocoaChina: iOS中的定时器 iOS中定时器有三种,分别是NSTimer、CADispl...

  • GCD定时器使用

    iOS中的常用定时器分为这几类: NSTimer CADisplayLink GCD定时器 选择GCD定时器原因:...

  • iOS:NSTimer的几种创建方式

    在iOS开发中,经常会用到定时器,iOS中常用的定时器有三种:NSTimer,GCD,CADisplayLink。...

  • 定时器的使用介绍

    iOS中的定时器大致分为这几类: NSTimer CADisplayLink GCD定时器 (一)NSTimer ...

  • iOS Timer

    iOS开发中定时器经常会用到,iOS中常用的定时器有三种,分别是NSTime,CADisplayLink和GCD。...

  • iOS三大定时器

    iOS开发中定时器经常会用到,iOS中常用的定时器有三种,分别是NSTime,CADisplayLink和GCD。...

  • Flutter 网络请求类封装及搜索框实现

    Flutter 中定时器的使用 在 Flutter 中定时器相对 iOS 来说比较好的一点就是定时器事件的执行不会...

  • 无标题文章

    iOS NSTimer使用详解-开启、关闭、移除 定时器定时器详解ios定时器关闭定时器NSTimer 1、要使用...

  • iOS 定时器耗电探究

    iOS开发中的几种定时器 iOS开发中定时器实现方式大致有三种,一种是Timer实现,一种是通过GCD自己创建,另...

网友评论

      本文标题:iOS 中的定时器

      本文链接:https://www.haomeiwen.com/subject/gejpactx.html