Reputation: 10827
I've seen there is a sleep method in the Win32 API and also a timer class to delay function calls.
Is there something similar that I can use on Mac OS?
I want a simple solution to create some sort of setTimeout
function found in JavaScript and AS3.
Upvotes: 1
Views: 1131
Reputation: 6062
You may do it using 2 methods:
1) Use NSObject
's performSelector:withObject:afterDelay:
2) Use Grand Central Dispatch, like this:
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, interval * NSEC_PER_SEC);
dispatch_after(delay, dispatch_get_main_queue(), ^{
your code here
});
Or, for shorter syntax, you may add the following functions somewhere to your project:
void Dispatch_AfterDelay(dispatch_queue_t queue, NSTimeInterval afterInterval, dispatch_block_t block)
{
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, afterInterval * NSEC_PER_SEC);
dispatch_after(delay, queue, block);
}
void Dispatch_AfterDelay_ToMainThread(NSTimeInterval afterInterval, dispatch_block_t block)
{
Dispatch_AfterDelay(dispatch_get_main_queue(), afterInterval, block);
}
And then you just call:
Dispatch_AfterDelay_ToMainThread(5.0, ^{
your code
});
Upvotes: 4
Reputation: 18253
If you can write a C function (or a block) to wrap your C++ code, then you can use Grand Central Dispatch.
Look at dispatch_after_f
for a delayed call of a function or dispatch_after
for its block based equivalent.
Upvotes: 0
Reputation: 89509
CFTimer
actually exists in Core Foundation, which is C++ & C compatible.
It's not very well documented at all, from what I can tell. Here is a related question that mentions it.
On a higher level, there's also the standard C call of sleep
(I've linked the man page for you here), and if you want to do this as a setTimeout
type of function you could figure out a way to do sleep
from a separate thread and then when it finishes (without being killed), consider things "timed out".
Upvotes: 2