johndbritton
johndbritton

Reputation: 2652

How can I display the number of seconds until an NSTimer next fires

I have a simple OSX Menubar application, the status item has a menu attached to it and I have a menu item that can manually send a fire to a NSTimer.

I'd like for that menu item to display the number of seconds until the next time the timer will be fired. Is there a way to get the amount of time until the next fire or the time at which the NSTimer will be next fired?

Upvotes: 1

Views: 435

Answers (2)

danyowdee
danyowdee

Reputation: 4698

I know there’s already an accepted answer, but it just occurred to me, that you actually may not be interested in the fireDate, at all:

Using that date, you’ll only see the same number of seconds, for as long as the time is displayed — if it’s displayed directly in the menu bar, there is no indication of progress…

I’d therefor suggest a slightly different approach:

  1. Calculate, and store the expiry date.
  2. Schedule a repeating timer, that fires at an interval matching your displayed precision, and updates the remaining time display, using the stored expiry date.
  3. As soon, as you’ve passed the expiry date, invalidate the timer, and do whatever it is you want to do, then.

So, why not use a one second timer, and a decrementing counter variable, then?

Simple: NSTimer is not a real-time thing. The actual date a timer fires, and its scheduled fireDate will be slightly different. But since repeating timers re-schedule without adjusting for that difference, these deviations add up.

These deviations are completely unpredictable, as they depend not only on the load of your App, but the system as a whole. So they will vary between “completely neglible”, and “ZOMFG”!

Upvotes: 2

jlujan
jlujan

Reputation: 1188

NSTimer has fireDate wich returns a NSDate. NSDate has timeIntervalSinceNow.

Upvotes: 4

Related Questions