Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

larswik

macrumors 68000
Original poster
Sep 8, 2006
1,552
11
Have a quick question to see if there is a better way of doing this. Basically I have an app that might be open for many days and it is important to advance the date at midnight. I can add [NSDate date]; to the awakeFromNib method to get the current date adn assign that value to an NSTextField label. Then using an NSTimer have it check every minute for the current date to update.

Would that be the best approach?
 
NSTimer

The first time you trip the "hey it's midnight" in your once-per-minute timer, reset that timer to once-per-24-hours.
 
When the app first loads calculate the time till midnight and use the NSTimer to trigger based on that and then once it triggers at midnight just reset to trigger again in 24 hours. Constantly checking is just overkill.
 
The 24 hour wait approach is nice but will eventually fail if "midnight" needs to occur at the local 23:59 -> 00:00 transition, as things like daylight savings time will add/subtract an extra hour on certain dates in certain countries (Locals).

Also be aware that daylight savings time results in certain times being skipped or occurring twice depending on if the clock is move forward or back 1 hour. These transitions are usually done a few hours after midnight so should (probably) not pose any issues.

Also take into account that users may change timezone/clock settings which means that a "24 hour wait" in progress will need to be canceled and redone.

If second level accuracy is important (it doesn't appear to be so) there may also be issues with things like leap seconds. There could also be minor deviations/delays due to exactly when the timer triggers and how much time is used to handle the event before starting the next 24 hour wait.
 
Cool, so NStimer was the best solution. I will use the rest at midnight for 24 hours. There is no need for the app to worry about day light savings time.

Thanks for the help guys!
 
This Stack Overflow post explains why this approach might not work all that well. The main issue I can see is that your timer will suspend its countdown should the system ever go to sleep.

From the post, I'd recommend using initWithFireDate:… for your timer, and registering to wake and clock change events as moments to recalculate the current date and reset your timer.
 
Interesting, I will look into it. Thanks.

-Lars

This Stack Overflow post explains why this approach might not work all that well. The main issue I can see is that your timer will suspend its countdown should the system ever go to sleep.

From the post, I'd recommend using initWithFireDate:… for your timer, and registering to wake and clock change events as moments to recalculate the current date and reset your timer.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.