-
Notifications
You must be signed in to change notification settings - Fork 0
18 — DispatchSource
A kitchen timer that rings on its own, without a chef having to keep glancing at the clock — the kitchen sets it up once and gets notified automatically.
DispatchSource provides low-level event monitoring — timers (DispatchSourceTimer), file system changes, process signals — that fire a handler automatically when the event occurs, without polling.
[timer] ──1s──▶ fire ──▶ handler()
──1s──▶ fire ──▶ handler()
──1s──▶ fire ──▶ handler()
let timer = DispatchSource.makeTimerSource(queue: .main)
timer.schedule(deadline: .now(), repeating: 1.0)
timer.setEventHandler {
print("Tick ⏰")
}
timer.resume()An AsyncSequence (e.g. a custom async timer sequence consumed with for await) can wrap similar recurring-event behavior for consumption in a structured, cancelable async context.
A DispatchSource is a timer the kitchen doesn't have to watch.
A physical kitchen timer only does time; DispatchSource covers a wider variety of low-level system events (files, signals, processes) the restaurant analogy doesn't map to as cleanly.
Why must you call .resume() after configuring a DispatchSourceTimer?