美文网首页
Swift自动释放的GCD的Timer 非常方便的使用

Swift自动释放的GCD的Timer 非常方便的使用

作者: 盟主直播Libx | 来源:发表于2019-10-08 15:00 被阅读0次

/** GCD + Extension */

extension DispatchQueue {

 // 定时器 Timer observer,跟定时器绑定的对象,对象销毁,定时器也自动销毁,timeInterval,间隔时间

public static func timer(observer: AnyObject, timeInterval: Int, handle: @escaping (_ timer: DispatchSourceTimer) -> Void) {

         let dsTimer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global())

         dsTimer.schedule(deadline: DispatchTime.now(), repeating: .seconds(timeInterval), leeway: .milliseconds(10)) 

                 dsTimer.setEventHandler { [weak observer] in

                         if observer == nil {                

                             dsTimer.cancel()            

                          } else { 

                            DispatchQueue.main.async { 

                                handle(dsTimer)

                 }           

          }        

 }    

    dsTimer.resume()    

 } 


调用的时候 DispatchQueue.timer


相关文章

网友评论

      本文标题:Swift自动释放的GCD的Timer 非常方便的使用

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