Skip to content

18 — DispatchSource

rebeloper edited this page Jul 12, 2026 · 1 revision

🍽️ Intuition

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.

🧠 What It Means In Swift

DispatchSource provides low-level event monitoring — timers (DispatchSourceTimer), file system changes, process signals — that fire a handler automatically when the event occurs, without polling.

📊 ASCII Diagram

[timer] ──1s──▶ fire ──▶ handler()
        ──1s──▶ fire ──▶ handler()
        ──1s──▶ fire ──▶ handler()

💻 Tiny Swift Example

let timer = DispatchSource.makeTimerSource(queue: .main)
timer.schedule(deadline: .now(), repeating: 1.0)
timer.setEventHandler {
    print("Tick ⏰")
}
timer.resume()

🔄 vs. Swift Concurrency

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.

🧸 Memory Sentence

A DispatchSource is a timer the kitchen doesn't have to watch.

⚠️ Analogy Limit

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.

✅ Check Your Understanding

Why must you call .resume() after configuring a DispatchSourceTimer?

Clone this wiki locally