3

I find myself in need for a repeating block of code I can execute. If I were in an object I could simply pass self to the NSTimer scheduling. I am in a pure C project at the moment and I don't see any obvious NSTimer analogs. Is there a correct way to approach this?

Alex Bollbach
  • 4,370
  • 9
  • 32
  • 80

2 Answers2

1

If you really want the CF way of doing this:

CFRunLoopTimer is the CoreFoundation counter-part you're probably looking for.

You'll need to construct a separate CFRunLoop on a different thread if you want the timer to fire an asynchronous job. Otherwise, you can use use the main application thread by calling CFRunLoopGetCurrent() and set that to be the "parent loop" (called a "mode") that responds to the timer's events.


Here's what you do:

  1. Initialize a CFRunLoopTimerContext struct (on the stack is fine)
  2. Calculate the next time at which the run loop fires using type CFAbsoluteTime and CFAbsoluteTimeGetCurrent() plus some CFTimeInterval (can be a double aka CGFloat)
  3. Create the run loop timer with CFRunLoopTimerCreate, passing in the next fire time and the callback function pointer
  4. Add the run loop timer to either a runloop on a separate thread or the main thread of the executable (see above)
Community
  • 1
  • 1
Sean
  • 5,233
  • 5
  • 22
  • 26
  • ... but using [Grand Central Dispatch](https://gist.github.com/maicki/7622108) as @trojanfoe recommended above will likely yield a more optimised binary when compiled. – Sean Sep 21 '16 at 19:51
0

I don't know much of anything about the foundation framework but you can hack together a timer using the mach/POSIX APIs which allow you to tap into kernel services and processes for your C application.

Using a combination of mach_absolute_time() and nanosleep() system calls may allow you to emulate a timer. It's a bit nasty if you've never done any systems programming on a *NIX like platform.

On Linux, it's much easier to implement a POSIX timer or make use of clock_gettime() and clock_nanosleep (POSIX functions) which are not available on the mac.

There's lots of info on Linux/Unix systems programming in C but not so much on a mac, so I'd recommend having a look at this question.

Also, I made my own little emulation of clock_gettime() and clock_nanosleep for the mac (shameless plug) Find it here

Community
  • 1
  • 1
ChisholmKyle
  • 449
  • 3
  • 10