Timer

作用

  • 在指定的时间执行指定的任务。
  • 每隔一段时间执行指定的任务。

1、定时器的创建

当定时器创建完(不用 scheduled 的,添加到 runloop 中)后,该定时器将在初始化时指定的 ti 秒后自动触发。

scheduled 方式:

/*
参数:
TimeInterval:触发时间,单位秒
target:定时起触发对象
selector:定时器响应方法
userInfo:用户信息
repeats:是否重复执行,YES 每个指定的时间重复执行,NO 只执行一次
*/

// 创建并启动定时器
let timer:Timer =  Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
  • 创建并启动定时器。
  • 默认将时钟以 NSDefaultRunLoopMode 模式添加到运行循环。
  • 发生用户交互的时候,时钟会被暂停。

timer 方式:

  • 创建定时器,添加到运行循环后启动定时器。
  • 将时钟以指定的模式添加到运行循环。
/*
 mode:
 NSDefaultRunLoopMode: 时钟,网络。           发生用户交互的时候,时钟会被暂停
 NSRunLoopCommonModes: 用户交互,响应级别高。  发生用户交互的时候,时钟仍然会触发,如果时钟触发方法非常
 耗时,使用此方式时用户操作会造成非常严重的卡顿。
 */

// 创建定时器
let timer:Timer = Timer(timeInterval: 2.0,target: self,selector: #selector(updateTimer),userInfo: nil,repeats: true)

// 将定时器添加到运行循环
RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes)

2、定时器的启动与关闭

以下方法可以控制添加到运行循环中的定时器,启动,暂停,销毁,如果被销毁的定时器将永远无法再启动

// 启动定时器
timer.fireDate = Date.distantPast

// 暂停定时器
timer.fireDate = Date.distantFuture

// 关闭定时器,永久关闭定时器
timer.invalidate()

3、子线程定时器的创建

var num = 0

DispatchQueue.global().async {
    let timer:Timer = Timer(timeInterval: 2.0, target: self, selector: #selector(self.updateTimer), userInfo: nil, repeats: true)

    RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)

    CFRunLoopRun()
}

func updateTimer() {
    num  = num + 1

    // 满足条件后,停止当前的运行循环
    if num == 8 {

        // 停止当前的运行循环
        /*
         一旦停止了运行循环,后续代码能够执行,执行完毕后,线程被自动销毁
         */
        CFRunLoopStop(CFRunLoopGetCurrent())
    }
}

4、定时任务

GCD方式

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3.0) {
    print("after!")
}

Timer

Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)

results matching ""

    No results matching ""