我有一个必须每半秒执行一次的代码,并且我正在使用 Xcode Playground。我用过这个top answer并得到这样的代码:
for (index, item) in array.enumerated() {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(index), execute: {
print("\(index) - \(df.string(from: Date()))"
//play sound every second
})
}
这段代码每秒执行一次(我知道我必须将其除以 2 才能得到半秒,但想查看结果)。我使用 DateFormatter
来计算时间,因为我无法弄清楚为什么声音播放不均匀。
let df = DateFormatter()
df.dateFormat = "ss.SSSS"
结果是它并不是每1秒触发一次。
0 - 17.4800
1 - 18.5770 // even though it's not called exactly after 1s it's acceptable
2 - 19.6750
3 - 20.7770
4 - 21.8780
5 - 22.9760
6 - 24.0710
7 - 25.1690
8 - 26.2720
9 - 27.3640
10 - 28.4760
11 - 28.7580 //0.3s of difference
12 - 30.4800
13 - 30.5060 // 0.1s of difference
14 - 32.4800
15 - 32.5030 // less than 0.1s of difference
最佳答案
这里你异步执行你的Print
语句,这样你就不会在半秒(或一秒)后得到你的打印数据。如果你同步执行它,那么你会以1秒的间隔得到你的打印数据。要了解有关调度队列的更多信息,请关注 this链接。如果您有任何问题,请告诉我。
关于swift - 在 Swift 中使用 DispatchQueue 时出现时间差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49347450/