sam-w
sam-w

Reputation: 7687

Why is my CFRunLoopTimer not firing?

I have a CFRunLoopTimer created within a C++ class as shown below:

#import <CoreFoundation/CoreFoundation.h>

void cClass::StartTimer()
{      
  if(!mActiveSenseTimer)
  {
    CFTimeInterval TIMER_INTERVAL = 5;
    CFRunLoopTimerContext TimerContext = {0, this, NULL, NULL, NULL};
    CFAbsoluteTime FireTime = CFAbsoluteTimeGetCurrent() + TIMER_INTERVAL;
    mTimer = CFRunLoopTimerCreate(kCFAllocatorDefault,
                                  FireTime,
                                  0, 0, 0,
                                  ActiveSenseTimerCallback,
                                  &TimerContext);

    NSLog(@"RunLoop:0x%x, TimerIsValid:%d, TimeIsNow:%f, TimerWillFireAt:%f",
          CFRunLoopGetCurrent(),
          CFRunLoopTimerIsValid(mActiveSenseTimer),
          CFAbsoluteTimeGetCurrent(),
          FireTime);
  }
}

void ActiveSenseTimerCallback(CFRunLoopTimerRef timer, void *info)
{
  NSLog(@"Timeout");
  CFRunLoopTimerContext TimerContext;
  TimerContext.version = 0;

  CFRunLoopTimerGetContext(timer, &TimerContext);
  ((cClass *)TimerContext.info)->Timeout();
}

Calling cClass::StartTimer() results in the following log output:

RunLoop:0x7655d60, TimerIsValid:1, TimeIsNow:389196910.537962, TimerWillFireAt:389196915.537956

However, my timer never fires. Any ideas why?

Upvotes: 4

Views: 1806

Answers (1)

Alexei Sholik
Alexei Sholik

Reputation: 7469

Quote from the docs

A timer needs to be added to a run loop mode before it will fire. To add the timer to a run loop, use CFRunLoopAddTimer. A timer can be registered to only one run loop at a time, although it can be in multiple modes within that run loop.

Also make sure your run loop doesn't die before the timer fires.

Upvotes: 4

Related Questions