Several common onestimerThe implementation of:

1.NStimer
  • init
//1. If the timer is not added to the RunLoop, the call timer.fire() will only be executed once. After adding the RunLoop, there is no need to call timer.fire() timer = timer.init (timeInterval: 1, target: self, selector:#selector(timerFire), userInfo: nil, repeats: true)//timer.fire() //2. Common runloop.current. Add (timer,forMode: .default)

Copy the code
  • scheduledTimer
// Timer = timer. ScheduledTimer (withTimeInterval: 1, repeats:true, block: { (timer) in
    print(timer)
 })
Copy the code
  • If I hadn’t puttimerAdded to theRunLoop, calltimer.fire()This will only be done once, addRunLoopYou don’t need to call it againtimer.fire()
  • The general default isdefaultBut when the UI is scrollingtimerIf yes, you can set this parameter tocommonHis accuracy dependsRunLoopThe state of the
2.DispatchSourceTimer
/ / accurate - the GCD timer / / packaging / / a set of the GCD PRODUCER environment from the UI rolling response / / initialization gcdTimer = DispatchSource makeTimerSource gcdTimer ()? .schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(1)) gcdTimer? .setEventHandler(handler: {print("hello GCD"}) // The default is suspended. .resume()Copy the code
  • Loaded a set of COMMUNIST party CDSPRODUCERThe environment
  • Not subject to UI scrolling response, relatively high accuracy
3.CADisplayLink
cadTimer = CADisplayLink(target: self, selector: #selector(timerFire)) cadTimer? .preferredFramesPerSecond = 1// Also need to add runLoop, also affected by UI scrolling cadTimer? .add(to: RunLoop.current,forMode: .default)
Copy the code
  • CADisplayLinkCannot be inherited
  • You also need to joinrunLoopIs also affected by UI scrolling
4.RxSwift Timer
Timer = Observable<Int>. Interval (1, scheduler: DispatchSourceTimer, DispatchSourceTimer, DispatchSourceTimer, DispatchSourceTimer, DispatchSourceTimer, DispatchSourceTimer) MainScheduler.instance) timer.subscribe(onNext: { (num)in
            print(num)
        })
    	.disposed(by: disposeBag)
Copy the code
  • The bottom isDispatchSourceTimerThe encapsulation
5. Summary of implementation methods