Open In App

Repeating Timers in Swift

Last Updated : 27 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Swift, a timer is a mechanism for scheduling code to run at a specified interval. A repeating timer is a type of timer that runs at a fixed interval and repeats indefinitely until it is stopped. 

How to Create a Repeating Timer in Swift

Here are the steps to create a repeating timer in Swift:

Step 1: Create a Timer object using the Timer.scheduledTimer method. This method takes four arguments:

  • timeInterval: The amount of time between each repetition of the timer (in seconds).
  • target: The object that should receive the timerFired method call when the timer fires.
  • selector: The method that should be called when the timer fires.
  • userInfo: Optional data to pass to the timerFired method when the timer fires.

Step 2: Start the timer using the fire() method on the Timer object.

Step 3: Implement the timerFired method in the target object. This method will be called each time the timer fires.

Here’s an example code that creates a repeating timer that fires every 2 seconds and prints a message to the console:

Swift




class TimerExample {
    var timer: Timer?
      
    func startTimer() {
        timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
        timer?.fire()
    }
      
    func stopTimer() {
        timer?.invalidate()
        timer = nil
    }
      
    @objc func timerFired() {
        print("Timer fired!")
    }
}
  
let example = TimerExample()
example.startTimer()


Output:

Output 1

 

Subtopics related to Repeating Timers in Swift

Invalidating a Timer

To stop a repeating timer, you need to call the ‘invalidate’ method on the Timer object. This will stop the timer from firing again. Here’s an example:

Invalidating a Timer

 

Scheduling a Timer on a Background Thread

By default, timers are scheduled on the main thread. However, if you need to run a timer on a background thread, you can use the ‘Timer.scheduledTimer(withTimeInterval:repeats:block:)’ method instead of ‘Timer.scheduledTimer’. This method takes three arguments:

  • timeInterval: The amount of time between each repetition of the timer (in seconds).
  • repeats: A Boolean value indicating whether the timer should repeat.
  • block: The block of code to execute each time the timer fires. 

Here’s an example code that creates a repeating timer on a background thread:

Swift




let queue = DispatchQueue.global(qos: .background)
  
let timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { timer in
    print("Timer fired!")
}
  
queue.async {
    RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
    RunLoop.current.run()
}


Rescheduling a Timer

You can also reschedule a timer to run at a different interval by invalidating the existing timer and creating a new one with a different time interval. Here’s an example:

Swift




class ReschedulingTimerExample {
    var timer: Timer?
    var timeInterval: TimeInterval = 2.0
      
    func startTimer() {
        timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
        timer?.fire()
    


Here are some additional subtopics and different ways related to the concept of repeating timers in Swift:

Setting a Timer’s Priority

By default, a timer is scheduled with a priority of default. We can change the priority of a timer using the ‘RunLoop’ method ‘add(_:forMode:)’. This method takes two arguments:

  • timer: The timer to add to the run loop.
  • mode: The run loop mode in which to add the timer.

Here’s an example code that sets the priority of a repeating timer to ‘userInteractive’:

Swift




let timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { timer in
    print("Timer fired!")
}
  
RunLoop.current.add(timer, forMode: .commonModes)
RunLoop.current.run(mode: .commonModes, before: Date.distantFuture)


Using GCD Timers

Instead of using the Timer class in Swift, we can also use Grand Central Dispatch (GCD) timers. GCD timers provide a more efficient way of scheduling code to run at a specific interval. Here’s an example code that creates a repeating GCD timer that fires every 2 seconds and prints a message to the console:

Swift




let queue = DispatchQueue.global(qos: .background)
  
let timer = DispatchSource.makeTimerSource(queue: queue)
  
timer.schedule(deadline: .now(), repeating: .seconds(2))
  
timer.setEventHandler {
    print("Timer fired!")
}
  
timer.resume()


Using Combine Timers

In Swift 5.0 and later, we can use Combine timers to create repeating timers. Combine is a framework that provides a declarative way to work with asynchronous operations. Here’s an example code that creates a repeating Combine timer that fires every 2 seconds and prints a message to the console:

Swift




import Combine
  
var cancellable: AnyCancellable?
  
cancellable = Timer.publish(every: 2.0, on: .main, in: .common)
    .autoconnect()
    .sink { _ in
        print("Timer fired!")
    }


With Combine timers, we can also use the ‘throttle’ operator to debounce events and the ‘delay’ operator to delay events. These operators provide more advanced control over the timing of events in your app.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads