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?
-
C has no timers in the standard. You need to use platform-specific APIs. – n. m. could be an AI Feb 11 '16 at 05:49
-
in that case is there a suitable alternative in Core Foundation? – Alex Bollbach Feb 11 '16 at 05:55
-
No idea, but you probably should use an appropriate tag in your question. – n. m. could be an AI Feb 11 '16 at 05:58
-
1What about GCD timer sources? (dispatch_* family) – nielsbot Feb 11 '16 at 07:30
-
1Grand Central Dispatch. See [this example](https://gist.github.com/maicki/7622108). – trojanfoe Feb 11 '16 at 07:30
2 Answers
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:
- Initialize a
CFRunLoopTimerContext
struct (on the stack is fine) - Calculate the next time at which the run loop fires using type
CFAbsoluteTime
andCFAbsoluteTimeGetCurrent()
plus someCFTimeInterval
(can be adouble
akaCGFloat
) - Create the run loop timer with
CFRunLoopTimerCreate
, passing in the next fire time and the callback function pointer - Add the run loop timer to either a runloop on a separate thread or the main thread of the executable (see above)
-
... 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
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

- 1
- 1

- 449
- 3
- 10