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

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值