I have this code:
let timer1 = Timer(timeInterval: 1, repeats: true) { _ in
print("FOO1")
}
let timer2 = Timer(timeInterval: 1, repeats: true) { _ in
print("FOO2")
}
let timer3 = Timer(timeInterval: 1, repeats: true) { _ in
print("FOO3")
}
let queue = DispatchQueue(label: "")
queue.async {
RunLoop.current.add(timer1, forMode: .common)
RunLoop.current.run()
}
queue.async {
RunLoop.current.add(timer2, forMode: .common)
}
queue.async {
RunLoop.current.add(timer3, forMode: .common)
}
In the current code, only timer1
is run. This is strange, because timer2
and timer3
are added to a running runloop. I recall in the main run loop (which is already running so I don’t have to call run again), I can simply add timers I want to add, and the timers will get triggered no problem.
My findings:
- If I move
RunLoop.current.run()
to the last async block, then all timers will be run. - If I add
RunLoop.current.run()
to all the 3 async blocks, onlytimer1
is run. - Changing
.common
to.default
mode won’t help
I am wondering why is my runloop behaving differently than the main runloop, and how can i mimic the behavior of main runloop?