zoukankan      html  css  js  c++  java
  • swift多线程定时器

    swift多线程定时器的使用

     func countDown(_ timeOut:Int,view: UIView){

            var timeout = timeOut

            let queue:DispatchQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default)

            

            if timer == nil {

                timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: 0), queue: queue) /*Migrator FIXME: Use DispatchSourceTimer to avoid the cast*/ as? DispatchSource

            }

            timer.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.seconds(0))

           // timer.setTimer(start: DispatchWallTime(time: nil), interval: 1*NSEC_PER_SEC, leeway: 0)

            //每秒执行

            timer.setEventHandler(handler: { () -> Void in

                if (timeout<=0) { //倒计时结束,关闭

                    self.timer.cancel()

                    DispatchQueue.main.async(execute: { () -> Void in

                        //设置界面的按钮显示 根据自己需求设置

                        //print("倒计时")

                        view.removerAlertView()

                    })

                }else {//正在倒计时

                    let seconds = timeout % 60

                   // let strTime = NSString.localizedStringWithFormat("%.2d", seconds)

                    

                    DispatchQueue.main.async(execute: { () -> Void in

                        //设置界面的按钮显示 根据自己需求设置

                        self.timerLabel.text = "(seconds)"

                    })

                    timeout -= 1;

                }

                

            })

            timer.resume()

        }

    暂停

       var isSuspend = false

        @objc func tap(_ gesture: UITapGestureRecognizer) {

            if timer != nil && timer.isCancelled == false {

                if isSuspend {

                    timer.resume()

                } else {

                    timer.suspend()

                }

                isSuspend = !isSuspend

            }

        }

    销毁

        deinit {

            if isSuspend {

                timer?.resume() //先继续运行再销毁

            }

            timer?.cancel()

            timer = nil

        }

        

  • 相关阅读:
    nginx基本命令
    一堆LCT板子
    17?17!
    ……妈妈我会写维修数列了!
    bzoj3744 Gty的妹子序列
    Noip2016 总结&反思
    bzoj4025 二分图
    [SHOI2008]堵塞的交通traffic
    bzoj4237 稻草人
    BestCoder Round #90
  • 原文地址:https://www.cnblogs.com/duzhaoquan/p/10383337.html
Copyright © 2011-2022 走看看