如何以同步方式触发多个不同的计时器?
我想构建一个应用程序,用户在计时器之后连续进行练习。他可以决定计时器的NB和每个计时器的价值。它适用于一个计时器,但是当我有多个计时器时,我想以串行模式(fire timer1,并且只有在完成的fire timer2等时)发射它们。在这里,代码以及我看到的是,在上一个末端之前,计时器是异步的。我花了很多时间来寻找一种简单的方法来编码它(我不确定需要同步队列)。我检查了许多问题,但找不到类似的回答。有任何线索如何做?
@IBOutlet weak var timerLabel: UILabel!
var timer = Timer()
var myTimers = [5, 10, 8]
var myTimeCheck = 0
var seconds = 0
@IBAction func launchTimersPressed(_ sender: UIButton) {
for myTime in myTimers {
let queue = DispatchQueue(label:"com.queue.serial")
queue.sync {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateChrono), userInfo: nil, repeats: true)
print ("myTime = \(myTime)")
myTimeCheck = myTime
}
}
}
@objc func updateChrono() {
seconds += 1
timerLabel.text = "\(seconds)"
// checking if we arrive at end of time
print("seconds and myTime: \(seconds) and \(myTimeCheck) ")
if seconds == myTimeCheck {
timer.invalidate()
return // to move out
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要尝试在同步队列中运行计时器。那太愚蠢了。
看起来所有计时器每秒都会触发,并且总是调用相同的目标。因此,只要有一个不断运行的计时器即可。它将是一个“检查当前锻炼的状态”计时器。
让 var 保存一个 Double 数组,指示每个练习的秒数。更好的是,有一组代表练习的结构体。
当用户开始练习时,从数组中删除其结构并将其保存在变量 currentExercise 中。
当用户开始特定锻炼时,还要计算
exerciseCompletedTime
TimeInterval
。每次每秒触发一次的计时器时,查看当前时间是否≥
exerciseCompletedTime
。如果是,则将该练习标记为已完成,从练习数组中删除下一个练习结构,将其设置为当前练习,并计算新的 exerciseCompletedTime。Don't try and run timers in a synchronous queue. That's silly.
It looks like all your timers fire every second, and always invoke the same target. So just have one timer that runs constantly. It will be a "check the state of the current exercise" timer.
Have a var hold an array of Doubles that indicates the number of seconds for each exercise. Better yet, have an array of structs representing exercises.
When the user starts an exercise, remove its struct from the array and save it in a variable currentExercise.
When the user begins a specific exercise, also compute an
exerciseCompletedTime
TimeInterval
.Each time your once-a-second timer fires, see if the current time is ≥
exerciseCompletedTime
. If it is, mark that exercise as completed, remove the next exercise struct from the array of exercises, set that one up as the current exercise, and compute a newexerciseCompletedTime
.