Track real time usage on Cocoa app

Inspired by @PeterHosey's interesting comment on this question , I decided to implement a time tracking system.

how

  • Application starts, counter starts
  • The application ends, the entire duration is logged
  • At any time (even during runtime) that the total usage time exceeds the allowed time, the user is notified

However, I have a couple ... conceptual problems:

  • What will I track? Is it enough [NSDate date]

    ?
  • What if the user just changes their system date / time at some point?
  • Also, what specific methods of the delegate should be hooked up? I mean, where would you call the start / stop routines for the counting functions?

I'm all ears! :-)

+3


source to share


1 answer


Well, I don't think you need to use [NSDate date] for this. Why aren't you using the mach_absolute_time () function? To track the elapsed time, it can be some kind of timer (ticks, for example, every minute).

GCD timers are a simple flexible way to implement timers that you can pause and resume if needed (for example, if you want to pause it while the program is not in use.).



- (void)createTimerSource
{
  // myTimerQueue and trialTimer are class members
  myTimerQueue = dispatch_queue_create("label.yourapp.com", NULL);
  trialTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, myTimerQueue);
  dispatch_source_set_timer(m_ping_timer, dispatch_time(DISPATCH_TIME_NOW,TimerPeriod * NSEC_PER_MSEC), TimerPeriod * NSEC_PER_MSEC,NSEC_PER_SEC/10);
  // set event handler
  dispatch_source_set_event_handler(m_ping_timer,^{
      // the code to check time elapsed
   });
  // set the cancel handler 
  dispatch_source_set_cancel_handler(m_ping_timer,^{
      // release timer dispatch source
      if(trialTimer)
         dispatch_release(trialTimer);
      // release dispatch timer
      if(myTimerQueue)
         dispatch_release(myTimerQueue);
   });
  // created sources always suspended
  dispatch_resume(trialTimer); // to suspend the timer use dispatch_suspend(trialTimer)
}

      

+3


source







All Articles