基础用法
创建新线程(多线程定时器)
创建
NSTimer
加入
RunLoop
定义执行函数
运行
RunLoop
(多线程定时器)
实例1
// 握手部分超时监控
let handShakerTimeOut: NSTimeInterval = 5
private var handShakerTimer: NSTimer?
private func startHandShakerTimer() {
print("=== startHandShakerTimer ===")
let thread = NSThread(target: self, selector: Selector("handShakerTimerThreadOperation"), object: nil)
thread.start()
}
@objc private func handShakerTimerThreadOperation() {
handShakerTimer = NSTimer.scheduledTimerWithTimeInterval(handShakerTimeOut, target: self, selector: "handShakerTimeOutHandler", userInfo: nil, repeats: false)
if let timer = handShakerTimer {
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
NSRunLoop.currentRunLoop().run()
}
}
@objc private func handShakerTimeOutHandler() {
print("=== handShakerTimeOut ===")
resetInterface()
}
private func stopHandShakerTimer() {
print("=== stopHandShakerTimer ===")
handShakerTimer?.invalidate()
handShakerTimer = nil
}
实例2
// 统计持续时间
let unitInterval: NSTimeInterval = 0.5 * 1
var durationCount: UInt64 = 0
var duration: NSTimeInterval {
return unitInterval * NSTimeInterval(durationCount)
}
private var durationTimer: NSTimer?
private func startDurationTimer() {
let thread = NSThread(target: self, selector: Selector("durationTimerThreadOperation"), object: nil)
thread.start()
}
@objc private func durationTimerThreadOperation() {
pushTimer = NSTimer.scheduledTimerWithTimeInterval(unitInterval, target: self, selector: "durationTimerHandler", userInfo: nil, repeats: true)
if let timer = pushTimer {
print("开始计时")
durationCount = 0
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
NSRunLoop.currentRunLoop().run()
}
}
@objc private func durationTimerHandler() {
durationCount++
}
private func stopDurationTimer() {
durationTimer?.invalidate()
durationTimer = nil
print("停止计时")
print("持续时间: \(duration)秒")
}
主线程定时器
当使用NSTimer
的scheduledTimerWithTimeInterval
方法时。事实上此时Timer
会被加入到当前线程的Run Loop
中,且模式是默认的NSDefaultRunLoopMode
。而如果当前线程就是主线程,也就是UI线程时,某些UI事件,比如UIScrollView
的拖动操作,会将Run Loop
切换成NSEventTrackingRunLoopMode
模式,在这个过程中,默认的NSDefaultRunLoopMode
模式中注册的事件是不会被执行的。也就是说,此时使用scheduledTimerWithTimeInterval
添加到Run Loop
中的Timer
就不会执行。
所以为了设置一个不被UI干扰的Timer
,我们需要手动创建一个Timer
,然后使用NSRunLoop
的addTimer:forMode:
方法来把Timer
按照指定模式加入到Run Loop
中。这里使用的模式是:NSRunLoopCommonModes
,这个模式等效于NSDefaultRunLoopMode
和NSEventTrackingRunLoopMode
的结合。
例子
private var timer: NSTimer?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
print("主线程 \(NSThread.currentThread())")
//创建Timer, 这两个函数都能用
// timer = NSTimer(timeInterval: 2, target: self, selector: Selector("timerHandler"), userInfo: nil, repeats: true)
timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("timerHandler"), userInfo: nil, repeats: true)
guard let timer = timer else { return }
//使用NSRunLoopCommonModes模式,把timer加入到当前Run Loop中。
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
print("start timer: \(timer)")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
print("stop timer: \(timer)")
timer?.invalidate()
timer = nil
}
//timer的回调方法
func timerHandler() {
print("Timer \(NSThread.currentThread())")
}```
## 输出
主线程 <NSThread: 0x7fa99a507ae0>{number = 1, name = main}
start timer: <__NSCFTimer: 0x7fa99a5112a0>
Timer <NSThread: 0x7fa99a507ae0>{number = 1, name = main}
Timer <NSThread: 0x7fa99a507ae0>{number = 1, name = main}
stop timer: Optional(<__NSCFTimer: 0x7fa99a5112a0>)```
多线程定时器
上面讲的NSRunLoopCommonModes
和Timer
中有一个问题,这个Timer
本质上是在当前线程的Run Loop
中循环执行的,因此Timer
的回调方法不是在另一个线程的。那么怎样在真正的多线程环境下运行一个Timer
呢?
可以先试试NSThread
。同上,我们还是会把Timer
加到Run Loop
中,只不过这个是在另一个线程中,因此我们需要手动执行Run Loop
(通过NSRunLoop
的run
方法)
例子代码
extension WorkThreadViewController {
// 定时器
func startTimer() {
//在当前Run Loop中添加timer,模式是默认的NSDefaultRunLoopMode
timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("timerHandler"), userInfo: nil, repeats: true)
guard let timer = timer else { return }
//使用NSRunLoopCommonModes模式,把timer加入到当前Run Loop中。
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
viewModel?.log = "startTimer(): \(timer)"
NSRunLoop.currentRunLoop().run()
}
//timer的回调方法
func timerHandler() {
viewModel?.log = "Timer \(NSThread.currentThread())"
}
func stopTimer() {
viewModel?.log = "stopTimer(): \(timer)"
timer?.invalidate()
timer = nil
}
}
extension WorkThreadViewController {
override func viewDidLoad() {
super.viewDidLoad()
viewModel = LogViewModel()
viewModel?.log = "主线程: \(NSThread.currentThread())"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//创建并执行新的线程
let thread = NSThread(target: self, selector: Selector("startTimer"), object: nil)
thread.start()
viewModel?.log = "新的线程: \(thread)"
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
stopTimer()
}
}
class WorkThreadViewController: UIViewController {
@IBOutlet weak var logTextView: UITextView!
private var viewModel: LogViewModel? {
didSet {
guard let viewModel = viewModel else { return }
dispatch_async(dispatch_get_main_queue()) {
self.logTextView.text = viewModel.logText
}
}
}
private var timer: NSTimer?
}
struct LogViewModel {
// ui content
var logText = "log"
// action
var log: String? {
didSet {
guard let log = log else { return }
let message = "[\(NSDate())] \(log)"
logText = logText + "\(message)\n\t------\t\n"
print(message)
}
}
}
- extension 将代码分块
- 用ViewModel隔离显示
输出
[2015-11-10 14:06:35 +0000] 主线程: <NSThread: 0x7f8249f06f70>{number = 1, name = main}
[2015-11-10 14:06:35 +0000] 新的线程: <NSThread: 0x7f8249f195d0>{number = 2, name = main}
[2015-11-10 14:06:35 +0000] startTimer(): <__NSCFTimer: 0x7f8249d3ab50>
[2015-11-10 14:06:37 +0000] Timer <NSThread: 0x7f8249f195d0>{number = 2, name = (null)}
[2015-11-10 14:06:39 +0000] Timer <NSThread: 0x7f8249f195d0>{number = 2, name = (null)}
[2015-11-10 14:06:41 +0000] Timer <NSThread: 0x7f8249f195d0>{number = 2, name = (null)}
[2015-11-10 14:06:42 +0000] stopTimer(): Optional(<__NSCFTimer: 0x7f8249d3ab50>)```
# 后台定时器
要借助苹果上的音频播放类在后台执行的这个特权
# GCD定时器
比较复杂,等遇到了再研究
# 例子代码链接
[一个用Swift写的关于定时器的小Demo](https://github.com/zhangxusong888/TimerDemo)