欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

iOSDispatchSourceTimer定时器的具体使用,

来源: 开发者 投稿于  被查看 266 次 评论:274

iOSDispatchSourceTimer定时器的具体使用,


目录
  • 1. 概述
  • 2. DispatchSourceTimer
    • 2.1 GCD Timer 创建
    • 2.2 GCD Timer 配置
    • 2.3 GCD Timer 部署任务
    • 2.4 GCD Timer控制方法
    • 2.5 双重循环 DispatchSourceTimer
  • 参考文章

    1. 概述

    说起计时器,很多开发人员第一时间就会想起Timer,但是随着使用的深入,慢慢就发现Timer其实不是很好用,比如说TableView滑动时候不执行,Timer循环应用。

    2. DispatchSourceTimer

    DispatchSourceTimer,也就是大家通常叫的GCD Timer,是依赖于GCD的一种Timer,Runloop的底层代码中也用到这种Timer,可见GCD Timer并不依赖与Runloop。

    先看一下苹果的定义:

    A dispatch source that submits the event handler block based on a timer.

    2.1 GCD Timer 创建

    使用下面的方法即可创建一个DispatchSourceTimer对象。

    class func makeTimerSource(flags: DispatchSource.TimerFlags = [], queue: DispatchQueue? = nil) -> DispatchSourceTimer
    // 默认在主队列中调度使用
    let timer = DispatchSource.makeTimerSource()
    // 指定在主队列中调度使用
    let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
    // 指定在全局队列中调度使用
    let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global())
    // 指定在自定义队列中调度使用
    let customQueue = DispatchQueue(label: "customQueue")
    let timer = DispatchSource.makeTimerSource(flags: [], queue: customQueue)

    2.2 GCD Timer 配置

    配置Timer参数,需要使用DispatchSourceTimer协议的方法。可以安排一次或多次触发的Timer。Timer每次触发的时候,都会调用已部署的任务。

        // 从现在开始,每秒执行一次。
        timer?.schedule(deadline: DispatchTime.now(), repeating: .seconds(1), leeway: .nanoseconds(1))
        // 5秒之后执行任务,不重复。
        timer?.schedule(deadline: DispatchTime.now() + 5, repeating: .never, leeway: .nanoseconds(1))

    2.3 GCD Timer 部署任务

    当Timer配置完参数后,使用DispatchSourceProtocol协议的方法来部署要执行的任务。

    setEventHandler和setRegistrationHandler的区别:

    • setEventHandler:给Timer设置要执行的任务,包括一次性任务和定时重复的任务。回调方法在子线程中执行。
    • setRegistrationHandler:这个方法设置的任务只会执行一次,也就是在Timer就绪后开始运行的时候执行,类似于Timer开始的一个通知回调。回调方法在子线程中执行。

    例如下面的代码:

    var timer: DispatchSourceTimer?
    
    func initTimer() {
        // 默认在主队列中调度使用
        timer = DispatchSource.makeTimerSource()
        
        // 从现在开始,每秒执行一次。
        timer?.schedule(deadline: DispatchTime.now(), repeating: .seconds(1), leeway: .nanoseconds(1))
        // 5秒之后执行任务,不重复。

    // timer?.schedule(deadline: DispatchTime.now() + 5, repeating: .never, leeway: .nanoseconds(1))

        timer?.setEventHandler {
            DispatchQueue.main.async {
                print("执行任务")
            }
        }
        
        timer?.setRegistrationHandler(handler: {
            DispatchQueue.main.async {
                print("Timer开始工作了")
            }
        })
        timer?.activate()
    }

    执行结果如下:

    2020-11-28 02:20:00 +0000 Timer开始工作了
    2020-11-28 02:20:00 +0000 执行任务
    2020-11-28 02:20:01 +0000 执行任务
    2020-11-28 02:20:02 +0000 执行任务

    2.4 GCD Timer控制方法

    下面看一下Timer的一下控制方法及状态:

    • activate() : 当创建完一个Timer之后,其处于未激活的状态,所以要执行Timer,需要调用该方法。
    • suspend() : 当Timer开始运行后,调用该方法便会将Timer挂起,即暂停。
    • resume() : 当Timer被挂起后,调用该方法便会将Timer继续运行。
    • cancel() : 调用该方法后,Timer将会被取消,被取消的Timer如果想再执行任务,则需要重新创建。

    上面的这些方法如果使用不当,很容易造成APP崩溃,下面来看一下具体注意事项及建议:

    • 当Timer创建完后,建议调用activate()方法开始运行。如果直接调用resume()也可以开始运行。
    • suspend()的时候,并不会停止当前正在执行的event事件,而是会停止下一次event事件。
    • 当Timer处于suspend的状态时,如果销毁Timer或其所属的控制器,会导致APP奔溃。
    • 2020-11-28 02:20:00 +0000 Timer开始工作了
      2020-11-28 02:20:00 +0000 执行任务
      2020-11-28 02:20:01 +0000 执行任务
      2020-11-28 02:20:02 +0000 执行任务
      suspend()和resume()需要成对出现,挂起一次,恢复一次,如果Timer开始运行后,在没有suspend的时候,直接调用resume(),会导致APP崩溃。
    • 使用cancel()的时候,如果Timer处于suspend状态,APP崩溃。
    • 另外需要注意block的循环引用问题。

    2.5 双重循环 DispatchSourceTimer

    比如:我们需要一定时间情况下(数组长度*4),每隔一段时间打印对应下标(每个元素隔4秒打印),无限打印

    在下面例子的双重循环中使用 DispatchSourceTimer 你会发现print只打印了 dom some = 0 这个不是我们想要的效果

    var exaltedTimer: DispatchSourceTimer?
    
    func demo {
        let arr = [1,2,3,4]
    
        self.exaltedTimer = DispatchSource.makeTimerSource()
        self.exaltedTimer?.schedule(deadline: .now(), repeating: TimeInterval(arr.count*4))
    
        self.exaltedTimer?.setEventHandler(handler: {
    
            for (index, item) in arr.enumerated() {
    
                let timer2 = DispatchSource.makeTimerSource()
                timer2.schedule(deadline: .now()+4.0*CGFloat(index), repeating: .infinity)
                timer2.setEventHandler {
                    DispatchQueue.main.async {
                        print("do some = \(index)")
                    }
                }
                
                timer2.activate()
    
    
            }
        })
        self.exaltedTimer?.activate()
    }

    这个是因为timer2使用之后就被释放了,所以要cancel和resume配合使用,这样就实现了我们想要的效果了。

    var exaltedTimer: DispatchSourceTimer?
    
    var exaltedTimerArray: [DispatchSourceTimer] = []
    
    func demo {
    
        self.exaltedTimer?.cancel()
        for subTimer in self.exaltedTimerArray {
            subTimer.cancel()
        }
    
        let arr = [1,2,3,4]
    
        self.exaltedTimer = DispatchSource.makeTimerSource()
        self.exaltedTimer?.schedule(deadline: .now(), repeating: TimeInterval(arr.count*4))
    
        self.exaltedTimer?.setEventHandler(handler: {
    
            for (index, item) in arr.enumerated() {
    
                let timer2 = DispatchSource.makeTimerSource()
                timer2.schedule(deadline: .now()+4.0*CGFloat(index), repeating: .infinity)
                timer2.setEventHandler {
                    DispatchQueue.main.async {
                        print("do some = \(index)")
                    }
                }
                
                self.exaltedTimerArray.append(timer2)
                timer2.resume()
    
    
            }
        })
        self.exaltedTimer?.resume()

    参考文章

    https://blog.csdn.net/guoyongming925/article/details/110224064

    到此这篇关于iOS DispatchSourceTimer 定时器的具体使用的文章就介绍到这了,更多相关iOS DispatchSourceTimer 定时器内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

    您可能感兴趣的文章:
    • iOS中几种定时器的实现小结
    • IOS 中NSTimer定时器的使用
    • iOS中最全的各种定时器使用教程
    • iOS仿小红书呼吸灯动画(核心动画和定时器)两种方式实现
    • iOS开发定时器的三种方法分享
    • iOS中的NSTimer定时器的初步使用解析

    用户评论