This is a simple example of using Timer in Swift. I’ve seen some Stack Overflow advice that says Timer performs badly but had no backup to support this assertion.
Swift 4.1
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
print("Starting")
let t = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: false) { (timer) in
print("TIMER FIRED")
}
//t.fire()
print("Waiting...")
You must invoke scheduledTimer on the main thread. If you don’t, iOS will quietly never fire the timer.
Useful reading:
- How do I run Asynchronous callbacks in Playground
- Session 213 at WWDC 2016
- There a note "Be sure to start timers in the main thread” in Timer.scheduledTimer not firing