UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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)

3      

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.

3      

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.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.