英文:
Timer does not get called inside Grand Central Dispatch async
问题
我有一个简单的定时器,每1秒将在异步的Grand Central Dispatch中执行一个日志打印:
import Foundation
do {
let GDC = DispatchQueue.init(label: "GDC", attributes: .concurrent)
GDC.async {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
print(3333)
}
}
} catch let err {
print(err)
}
然而,在Playground中运行时,我看不到print或err的日志?
英文:
I have a simple timer each 1 second will execute logging print inside an async Grand Central Dispatch:
import Foundation
do {
let GDC = DispatchQueue.init(label: "GDC", attributes: .concurrent)
GDC.async {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
print(3333)
}
}
} catch let err {
print(err)
}
However I don't see the log of print or err when running in Playground?
答案1
得分: -1
在技术上,要解决这个问题,你需要使用 RunLoop.current.run()
创建一个永久循环。
所以:
do {
let GDC = DispatchQueue.init(label: "GDC", attributes: .concurrent)
GDC.async {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
print(3333)
}
RunLoop.current.run()
}
}
应该可以工作。然而,在这种情况下,你真的需要定时器吗,这是一个更大的问题。考虑使用 DispatchQueue.asyncAfter
作为一个例子(根据用例可能还有更多选项)。
英文:
Technically to solve the issue you need to create a permanent loop using RunLoop.current.run()
So:
do {
let GDC = DispatchQueue.init(label: "GDC", attributes: .concurrent)
GDC.async {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
print(3333)
}
RunLoop.current.run()
}
}
should work. However do you really need timers in this case is a bigger question. Consider using DispatchQueue.asyncAfter
for example (and possibly there are more options, depending on use case).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论