Search code examples
swifttimergrand-central-dispatch

Timer does not get called inside Grand Central Dispatch async


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?


Solution

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