Swift - GCD timer使用

private var timer: DispatchSourceTimer?
    
    func addTimer() {
         // 子线程创建timer
        timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global())
        //        let timer = DispatchSource.makeTimerSource()
        /*
         dealine: 开始执行时间
         repeating: 重复时间间隔
         leeway: 时间精度
         */
        timer?.schedule(deadline: .now() + .seconds(5), repeating: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.seconds(0))
        // timer 添加事件
        timer?.setEventHandler {
            print("timer事件")
        }
        timer?.resume()
    }
    // timer暂停
    func stopTimer() {
        timer?.suspend()
    }
    // timer结束
    func cancleTimer() {
        guard let t = timer else {
            return
        }
        t.cancel()
        timer = nil
    }

timer:https://github.com/100mango/SwiftTimer
定时器:https://github.com/dalu93/Each

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    wgl0419阅读 6,424评论 1 9
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,642评论 2 45
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,268评论 19 139
  • -1- 她一晚上把手机开了关,关了开,和他看电影回来还没六个小时,他的微信头像怎么换成另一个女人了,一个很时尚的女...
    rosesnail阅读 214评论 0 0
  • 作者简介: 阿尔伯特·埃利斯(1913—2007),超越弗洛伊德的著名心理学家,理性情绪行为疗法之父。作者自194...
    snowbean2004阅读 4,047评论 0 3