计时器在Grand Central Dispatch异步中未被调用。

huangapple go评论69阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2023年3月31日 20:36:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定