TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.