在不停止计时器的情况下重新开始:它会导致 运行 个 swift 中的多个计时器吗
Without stoping a timer, start again : will it cause running multiple timers in swift
我有如下功能:
func startTimer() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
DispatchQueue.main.async {
appDelegate.TIMER = Timer.scheduledTimer(withTimeInterval: self.REPEAT_TIME, repeats: true, block: { timer in
self.sendData(programID: self.MAIN_THREAD)
do {
try ...
}
catch let error {
...
}
})
}
}
定时器停止功能:
func stopTimer() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if (appDelegate.TIMER != nil) {
appDelegate.TIMER?.invalidate()
appDelegate.TIMER = nil
}
}
我想知道
如果我不停地调用这个函数,是否有机会启动多个定时器实例?
这个案例怎么样,(这是否只停止了一个计时器并继续 运行 另一个计时器?)
启动定时器→再次启动→停止
is there any chance to start multiple timer instances if I call this function without stopping?
是的,startTimer
将启动另一个计时器 w/o 停止前一个计时器,但是当您将它存储在 属性 TIMER
中时,您将失去对先前安排的计时器的引用,所以直到结束才能停止它。
And how about this case,(does this stopped only one timer & continue running another timer?)
Start the timer → Start again → Stop
是的,它将停止上次启动的计时器,所有其他先前启动的计时器将继续 self.REPEAT_TIME
。
我有如下功能:
func startTimer() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
DispatchQueue.main.async {
appDelegate.TIMER = Timer.scheduledTimer(withTimeInterval: self.REPEAT_TIME, repeats: true, block: { timer in
self.sendData(programID: self.MAIN_THREAD)
do {
try ...
}
catch let error {
...
}
})
}
}
定时器停止功能:
func stopTimer() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if (appDelegate.TIMER != nil) {
appDelegate.TIMER?.invalidate()
appDelegate.TIMER = nil
}
}
我想知道
如果我不停地调用这个函数,是否有机会启动多个定时器实例?
这个案例怎么样,(这是否只停止了一个计时器并继续 运行 另一个计时器?)
启动定时器→再次启动→停止
is there any chance to start multiple timer instances if I call this function without stopping?
是的,startTimer
将启动另一个计时器 w/o 停止前一个计时器,但是当您将它存储在 属性 TIMER
中时,您将失去对先前安排的计时器的引用,所以直到结束才能停止它。
And how about this case,(does this stopped only one timer & continue running another timer?) Start the timer → Start again → Stop
是的,它将停止上次启动的计时器,所有其他先前启动的计时器将继续 self.REPEAT_TIME
。