美文网首页
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 中的定时器

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