美文网首页
(实验)Swift GCD定时

(实验)Swift GCD定时

作者: LoseAnson洛施安森 | 来源:发表于2017-12-19 10:59 被阅读11次

    延迟执行

    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        print(Thread.current.description)
        print("Hello Anson!!")
    }
    print("Hello Word!")
    
    //Command Line tool程序中添加的    
    RunLoop.current.run()
    

    输出

    Hello Word!
    <NSThread: 0x101807600>{number = 1, name = main}
    Hello Anson!!
    

    定时器

    //设定定时时间为5s
    var countTime = 5
    // 在global线程里创建一个时间源
    let codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
    // 设定这个时间源是每1秒循环一次,立即开始
    codeTimer.schedule(deadline: .now(), repeating: .milliseconds(1000))
    // 设定时间源的触发事件
    codeTimer.setEventHandler(handler: {
        // 每秒计时一次
        print(Date().description +  "------ \(countTime)")
        countTime = countTime - 1
        // 时间到了取消时间源
        if countTime <= 0{
            codeTimer.cancel()
        }
    })
    //启动定时器
    codeTimer.activate()
    RunLoop.current.run()
    

    输出

    2017-12-19 02:57:25 +0000------ 5
    2017-12-19 02:57:26 +0000------ 4
    2017-12-19 02:57:27 +0000------ 3
    2017-12-19 02:57:28 +0000------ 2
    2017-12-19 02:57:29 +0000------ 1
    

    相关文章

      网友评论

          本文标题:(实验)Swift GCD定时

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