WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Running a task in background every second

Forums > macOS

Hi folks, I'm working on a pomodoro app for myself and I was wondering what's the best way to run something every second and be sure it always runs :)

The reason I want to do this is that I want to update a text file with the time left (or elapsed) :)

Does my question make sense? From what I understood timers are tied to the app interface, while this background should update the interface too, using a timer doesn't feel like it is the right thing to do (and I'm not sure I can guarantee it runs all the time)


I don't have a specific answer for you, but a search engine query for swift background timers turned up some links that may help.


The Timer class should work the same regardless of whether your Mac app is frontmost, in the background, hidden, or faceless.

There is another consideration to which I do not have the answer: whether the Timer class publisher ignores elapsed time while the Mac is asleep. You can easily test this by having the timer print to the log and see what happens when you put your Mac to sleep for a period several times longer than the timer repeat interval. My guess is that it includes sleep time because every Timer instance has a fireDate property.

FYI, in GrandCentralDispatch, you can schedule a DispatchSourceTimer by either wallDeadline or deadline, which respectively do and do not count the time while the Mac is asleep.


Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.