Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 146 ยท Standard Library and Foundation

Timers: Repeating, One-Shot and Task-Based

Learn every way to run code later or repeatedly in Swift - Timer with run loops, DispatchSourceTimer, Task.sleep and clocks - with runnable examples, tolerance, cancellation and a timeout helper.

Many programs need to do something "in a while" or "every second": hide a message after three seconds, refresh data every minute, retry a request with a delay, or give up when an operation takes too long. Swift has three families of tools for this, and they belong to three different eras. Timer is the classic Foundation class built on run loops. DispatchSourceTimer is the Grand Central Dispatch version, driven by a queue. And in modern code you usually do not need either, because Task.sleep inside a loop does the same job with plain async/await.

This lesson shows all three, explains the rules that make timers behave (or silently never fire), and ends with a small timeout helper. You should know the basics of tasks and cancellation; the dispatch part builds on threads and dispatch.

Timer: the run-loop timer

A Timer does nothing by itself. It is an object that a run loop checks. A run loop is an event loop that sleeps until something happens (a touch, a network event, a timer firing) and then runs the matching code. The main thread of an app already has a running run loop, so a timer created there just works. A command-line program has none until you start one, which is why the examples below keep the program alive on purpose.

Timer.scheduledTimer(withTimeInterval:repeats:block:) creates a timer and adds it to the current run loop in one step. When repeats is true, the timer fires again and again until you call invalidate().

Swift A repeating timer that stops itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program prints tick 1, tick 2, tick 3, then invalidated, isValid = false, and finally done after 3 ticks. Three things are worth noticing:

  • The timer receives itself in the closure, which makes invalidate() easy to call from inside.
  • invalidate() is the only way to stop a repeating timer, and it is permanent. The run loop keeps a strong reference to a valid timer, so a repeating timer that you forget to invalidate stays alive and keeps whatever its closure captured alive too. In a class, use [weak self] in the closure and invalidate the timer in the place that ends its job (see deinit and ARC).
  • tolerance says how late the timer may fire. Giving the system a little slack, for example 10% of the interval, lets it group wake-ups and save power. It never fires early.

The while timer.isValid loop is only needed in a command-line program. In an iOS or macOS app, the main run loop is already running, and in a SwiftUI view you would use a task or Timer.publish, shown later.

One-shot timers, fire() and run-loop modes

With repeats: false the timer fires once and then invalidates itself. You can also create a timer without scheduling it using Timer(timeInterval:repeats:block:), and then decide yourself which run loop and mode it goes into. Calling fire() runs the timer's closure right now, without waiting.

Swift One-shot timers, fire() and invalidation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

A run-loop mode is a named set of event sources. A timer only fires while the run loop is running in a mode that contains it. A timer made with scheduledTimer goes into .default. On Apple platforms that has a famous consequence: while a user is scrolling, the run loop switches to a tracking mode, and .default timers pause until the scroll ends. If a timer must keep firing during scrolling, add it with RunLoop.current.add(timer, forMode: .common). A timer that you create with Timer(...) and never add to a run loop never fires at all, which is the most common "my timer does nothing" bug.

DispatchSourceTimer: a timer on a queue

DispatchSource.makeTimerSource(queue:) makes a timer that is not tied to a run loop. It fires on a dispatch queue you choose, so it works on background threads, in daemons and anywhere else without a run loop. You configure it with schedule(deadline:repeating:leeway:), give it an event handler, and resume() it. The leeway parameter is the same idea as tolerance.

Swift A timer on a dispatch queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The class owns the source and the state, and a semaphore lets main wait until the cancel handler has run. Two rules apply to dispatch sources. First, a source starts suspended; nothing happens until resume(). Second, you must not release a source that is suspended or give it a different state without balancing calls, so cancel it with cancel() and let the cancel handler do the cleanup. Because the handler runs on a queue, state it touches must be protected: here the private queue is the only place that reads and writes count.

Task.sleep: the modern replacement

With Swift concurrency you can simply wait inside a task. Task.sleep(for:) suspends the task without blocking a thread, and it throws CancellationError if the task is cancelled while sleeping. A repeating job is then an ordinary loop, and stopping it is ordinary cancellation, with no run loop, no queue and no invalidation to remember.

Sleeping for a fixed interval inside a loop drifts, because the time the work itself takes is added on top. To keep a steady cadence, sleep until a deadline that you move forward by the interval each round, using a Clock.

Swift Loops, deadlines and cancellation with Task.sleep

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

ContinuousClock keeps counting while the computer sleeps, and SuspendingClock does not; choose the one that matches whether "one hour" means wall time or time awake. A sleeping task that is cancelled wakes up immediately and throws, which is why the catch block runs without waiting a whole second.

A ticker as an AsyncStream, and a timeout

Often you want ticks as a sequence, so a consumer can write for await. Wrapping the loop in an AsyncStream does exactly that, and onTermination makes sure the sleeping task stops when the consumer leaves the loop. The same sleeping-task idea builds a timeout: race the real work against a sleeper in a task group and keep whichever finishes first.

Swift A ticker stream and a timeout helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The fast call returns Optional(42) and the slow call returns nil, after about 30 ms and not two seconds, because cancelAll() wakes the sleeping operation. (This helper only works if the operation cooperates with cancellation, as Task.sleep does.) For streams in more depth see async sequences.

Combine's Timer.publish and other ways to wait

On Apple platforms, Combine offers Timer.publish(every:on:in:), a publisher that emits the current date on every tick. SwiftUI code often uses it with .onReceive. Combine is not part of Swift on Linux, so the snippet below is read-only:

Swift
// Apple platforms only (Combine is not available on Linux)
import Combine

let cancellable = Timer.publish(every: 1, on: .main, in: .common)
    .autoconnect()
    .sink { date in print("tick at \(date)") }

// later: cancellable.cancel()

DispatchQueue.main.asyncAfter(deadline: .now() + 2) { ... } runs one closure later and is fine for a single delay that does not need cancelling. If you might need to cancel, use a Task or a DispatchWorkItem instead.

Need Reach for
Delay in async code try await Task.sleep(for:)
Repeating job in async code a loop with clock.sleep(until:) in a Task
Repeating job in a UI on the main run loop Timer.scheduledTimer, or Timer.publish in SwiftUI
Repeating job on a background queue without async DispatchSourceTimer
One delayed closure DispatchQueue.asyncAfter

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A repeating Timer is created with scheduledTimer inside a class. What must you do to stop it, and to avoid a retain cycle?

    The run loop holds a strong reference to a valid timer, so releasing your own reference does nothing. Only invalidate() removes the timer, and a weak self in the closure stops the timer from keeping its owner alive.
  2. 2. A command-line program creates Timer.scheduledTimer(...) and then reaches the end of main. What happens?

    A timer needs a running run loop. The main thread of a command-line tool has none until you start one, for example with RunLoop.current.run(until:).
  3. 3. What does the tolerance property of a Timer allow?

    Tolerance is extra time after the scheduled moment during which the timer may fire. It never makes a timer fire early.
  4. 4. Why does a loop that does work(); try await Task.sleep(for: .seconds(1)) drift over time?

    Each round takes work time plus one second. Sleeping until a deadline that you advance by the interval, using clock.sleep(until:), keeps the cadence steady.
  5. 5. A DispatchSourceTimer was created and configured, but its handler never runs. What is the most likely missing step?

    Dispatch sources are created suspended. Nothing is delivered until resume() is called.

Summary

  • Timer is run-loop based: it needs a running run loop and the right mode, repeats until invalidate(), and the run loop keeps it alive.
  • tolerance (and leeway for dispatch sources) lets the system fire a little late to save energy; it never fires early.
  • fire() runs a timer's closure immediately; a one-shot timer becomes invalid after it fires.
  • DispatchSourceTimer fires on a queue, starts suspended, and is stopped with cancel().
  • In async code prefer Task.sleep and Clock.sleep(until:); cancellation stops a sleeping task at once, and a task group can race work against a sleeper to build a timeout.
  • Timer.publish is Combine and Apple-only, so it is shown read-only here.

Next: Dates, Calendars and Formatting