Timer Examples with Grand Central Dispatch in Swift

Explore practical examples of creating timers in Swift using Grand Central Dispatch for efficient task scheduling.
By Jamie

Introduction to Timers in Swift

Timers are essential in programming for scheduling tasks to be executed after a certain period. In Swift, Grand Central Dispatch (GCD) provides a powerful way to manage concurrent tasks, making it an excellent tool for creating timers. Below, we present three diverse examples of creating timers using GCD in Swift, each tailored to specific use cases.

Example 1: Simple Countdown Timer

Context

A simple countdown timer can be useful in various applications such as cooking timers, reminders, or countdowns for events. This example demonstrates how to create a countdown timer that executes a task every second until it reaches zero.

import Foundation

func startCountdownTimer(duration: Int) {
    var remainingTime = duration
    let timer = DispatchSource.makeTimerSource()

    timer.schedule(deadline: .now(), repeating: 1.0)
    timer.setEventHandler { 
        if remainingTime > 0 {
            print("Time remaining: \(remainingTime) seconds")
            remainingTime -= 1
        } else {
            print("Countdown finished!")
            timer.cancel()
        }
    }
    timer.activate()
}

startCountdownTimer(duration: 5)

Notes

  • This timer updates every second and prints the remaining time.
  • You can modify the duration parameter to set any countdown length.

Example 2: Repeating Task Timer

Context

Repeating task timers are useful in scenarios where you need to execute a task at regular intervals, such as updating a user interface or polling data from a server. This example shows how to create a timer that runs a function every 5 seconds.

import Foundation

func startRepeatingTaskTimer() {
    let timer = DispatchSource.makeTimerSource()

    timer.schedule(deadline: .now(), repeating: 5.0)
    timer.setEventHandler { 
        print("Repeating task executed at: \(Date())")
    }
    timer.activate()
}

startRepeatingTaskTimer()

Notes

  • This timer will execute the designated task every 5 seconds.
  • To stop the timer, call timer.cancel() from within the handler or from another function.

Example 3: Delayed Execution Timer

Context

A delayed execution timer is particularly useful when you need to perform an action after a specific delay, such as showing a notification or triggering an animation. In this example, we will implement a timer that executes a task after a delay of 10 seconds.

import Foundation

func startDelayedExecutionTimer() {
    let timer = DispatchSource.makeTimerSource()

    timer.schedule(deadline: .now() + 10.0)
    timer.setEventHandler { 
        print("This message appears after a 10 second delay!")
        timer.cancel()
    }
    timer.activate()
}

startDelayedExecutionTimer()

Notes

  • The timer is set to execute only once after a 10-second delay.
  • You can adjust the delay by changing the value in the schedule method.

Conclusion

These examples of creating a timer using Grand Central Dispatch in Swift illustrate how versatile and powerful GCD can be for managing time-dependent tasks in your applications. Whether you need a simple countdown, a repeating task, or a delayed execution, GCD provides a clean and effective solution.