Skip to Content
Course content

177: Timer for Scheduled Execution

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Let's imagine we're building a simple text editor. One feature I always want in these kinds of apps is an "Auto-save" indicator. You know the one—a little piece of text in the corner that says "Saving..." every few seconds so the user doesn't panic about their work.

Just making it tick

My first instinct is to just trigger a function every few seconds. In Swift, the go-to for this is Timer. I'll start with the most straightforward approach: scheduledTimer. I'll write a quick class to handle the saving logic and see if I can get it to fire.

class DocumentManager {
    func startAutoSave() {
        Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { timer in
            print("Auto-saving document at \(Date())...")
        }
    }
}

let manager = DocumentManager()
manager.startAutoSave()

If I run this in a playground or a long-running app, it works exactly as expected. Every three seconds, I see that print statement. Easy, right? But here is where things usually go sideways in a real project.

The "Zombie" Timer

I noticed something annoying during testing. If I destroy the DocumentManager instance—maybe the user closes the document—the timer keeps firing. I can still see "Auto-saving..." in my console even though the object that started it is long gone. This is a classic leak. Because Timer.scheduledTimer adds the timer to the current run loop, the run loop holds a strong reference to the timer, and the timer holds a strong reference to the closure.

I need a way to kill the timer manually. To do that, I can't just call the method in a vacuum; I need to keep a reference to the timer object itself.

class DocumentManager {
    var saveTimer: Timer?

    func startAutoSave() {
        // I'll store the timer in my optional property
        saveTimer = Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { timer in
            print("Auto-saving...")
        }
    }

    func stopAutoSave() {
        saveTimer?.invalidate()
        saveTimer = nil
        print("Timer stopped.")
    }
}


Now, by calling invalidate(), I'm telling the run loop to let go of the timer. This is non-negotiable for any timer you create; if you don't invalidate it, you're basically leaving a light on in a room you've already left.

The Memory Trap

There's one more thing. As I'm refining this, I realize that if my closure starts touching properties inside DocumentManager (like a documentContent string), I'm creating a strong reference cycle. The timer owns the closure, and the closure owns self (the DocumentManager). Even if I call stopAutoSave, if I forgot to do it in a deinit, the object might never actually be destroyed.

I'll fix this by using a weak self capture list. It's a habit I've developed over the years—whenever you see a timer closure, immediately ask yourself: "Who owns whom?"

class DocumentManager {
    var saveTimer: Timer?
    var documentName = "MyNotes.txt"

    func startAutoSave() {
        saveTimer = Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { [weak self] timer in
            // Now 'self' is optional. If the manager is gone, this block does nothing.
            guard let self = self else { return }
            print("Auto-saving \(self.documentName)...")
        }
    }

    deinit {
        saveTimer?.invalidate()
    }
}


Now it's clean. The timer is scheduled, it's reference-tracked so it can be stopped, and it doesn't hold the manager hostage in memory. It's a simple pattern, but missing any one of these steps usually leads to a bug that's a nightmare to track down in a large codebase.




📋 Practical Task

Build a Pomodoro Countdown Trigger

Create a class called PomodoroTimer that simulates a focus session. The class should meet the following requirements:

  • Maintain a secondsRemaining integer property (start it at 25 minutes, or 1500 seconds for testing).
  • Implement a startSession() method that uses a Timer to decrement secondsRemaining by 1 every second.
  • The timer must use [weak self] to avoid memory leaks.
  • Implement a stopSession() method that invalidates the timer.
  • The timer should automatically call stopSession() and print "Time is up!" when secondsRemaining reaches 0.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.