Swift’s Timer
class is a flexible way to schedule work to happen in the future, either just once or repeatedly. In this guide I will to provide a selection of ways to work with it, along with solutions for common problems.
import Foundation
class TimerExample {
// Timer instance
private var timer: Timer?
// Start the timer
func startTimer() {
// Invalidate any existing timer first
stopTimer()
// Create a new timer that fires every 120 seconds
timer = Timer.scheduledTimer(
timeInterval: 120.0,
target: self,
selector: #selector(timerFired),
userInfo: nil,
repeats: true
)
// If you want the timer to continue running while scrolling in a UI
RunLoop.current.add(timer!, forMode: .common)
print("Timer started - will fire every 120 seconds")
}
// Stop the timer
func stopTimer() {
timer?.invalidate()
timer = nil
print("Timer stopped")
}
// The method that will be called when the timer fires
@objc private func timerFired() {
print("Timer fired at: \(Date())")
// Your code to execute every 120 seconds goes here
performTask()
}
// Example task to perform when timer fires
private func performTask() {
print("Performing scheduled task")
}
}
// Usage example
let timerExample = TimerExample()
timerExample.startTimer()
// To stop the timer later
// timerExample.stopTimer()
// Keep the program running to see the timer in action
RunLoop.main.run(until: Date(timeIntervalSinceNow: 300))
This code:
- Creates a
TimerExample
class that encapsulates timer functionality - Sets up a timer to fire every 120 seconds (2 minutes)
- Includes methods to start and stop the timer
- Provides a callback method (
timerFired
) that executes when the timer fires - Runs the timer for 300 seconds as an example
If you’re working in a SwiftUI context, you might prefer using this alternative approach:
import SwiftUI
struct ContentView: View {
@State private var timerCount = 0
@State private var timer: Timer? = nil
var body: some View {
VStack {
Text("Timer count: \(timerCount)")
.font(.largeTitle)
Button("Start Timer") {
startTimer()
}
.padding()
Button("Stop Timer") {
stopTimer()
}
.padding()
}
.onDisappear {
stopTimer()
}
}
func startTimer() {
stopTimer() // Clear any existing timer
timer = Timer.scheduledTimer(withTimeInterval: 120, repeats: true) { _ in
timerCount += 1
print("Timer fired at: \(Date())")
// Perform your task here
}
}
func stopTimer() {
timer?.invalidate()
timer = nil
}
}
Thanks for reading!