Timers

A timer sends a message to an object after a certain amount of time passes. Start by declaring a variable for the timer.

var saveTimer = Timer()

Starting a Timer

Call the scheduledTimer method to start a timer. The scheduledTimer method takes the following arguments:

  • A time interval for how often the timer fires, specified in seconds.
  • Target, which is the object that receives the message from the timer.
  • Selector, which is the function the target should run after receiving the message.
  • UserInfo, which is optional additional information you can send.
  • Repeats, which indicates whether the timer runs once or repeats.

The following code starts a timer to autosave data every 30 seconds:

func startTimer() {
    saveTimer = Timer.scheduledTimer(timeInterval: 30.0, 
        target: self, selector: #selector(self.autosave), 
        userInfo: nil, repeats: true)
}

The function for the selector needs @objc at the start of the declaration.

@objc func autosave(timer: Timer) {

}

Stopping a Timer

Call the invalidate method to stop a timer. The following code stops a timer:

func stopTimer() {
    saveTimer.invalidate()
}