iOS – Timers and Threading


I’m in the process of improving my skills, knowledge, and experience with mobile development. Not only have I been learning more about different technologies in my professional work, but outside of my professional work as well. I’m always excited to learn new things and to enhance and really develop my skills.

Recently, I’ve been playing with timers and threading in swift. I took a programming quiz/test that asked me different questions about different methodologies and proper ways to creating solutions for possible application requirements, and one of them was specific to threading and processes. I want to create a quick app where I could create some different background threads but create a timer within these threads that would display a message to the console.

I first started with some code that looks like this –

Then as I would run the code, I would see a message in the console, informing me that the “Second thread [is] starting.” But I would never see my timer message displaying every 5 seconds. I tried calling self.secondTimer.fire() method and I would see it display one of my messages from the timer, but then it wouldn’t do any more after that. It turns out, after doing some research, that Timers don’t normally work on background threads. They work on the main UI thread.

After realizing that a timer doesn’t work on any background thread, I then changed my logic around to start a timer, then do a background thread that displays a message in the console. This is what I came up with –

This now creates a Timer, then it creates a thread within the timer and prints a message. I do, however, recognize something. Since I have it on repeat, it is creating a new thread every time the Timer block repeats. I will need to go back and properly end this thread or else I will be creating a memory leak, which is never good. :/  Or does it?