Cocoa analogue of Windows' SetTimer
Is there an OS X equivalent function for SetTimer on Windows? I am using C ++.
So I am writing a plugin for some software and I need to call a function periodically. On Windows, I just pass the address to the SetTimer () function and it will be called at the specified interval. Is there an easy way to do this on OS X? It should be as minimal as possible. I didn't really find anything out of the ordinary on the internet, there was something about the huge structure and another solution using a second thread that sleeps another time, but I think there should be an easier way.
source to share
Consider using the Boost Asio library . The deadline_timer class works on all platforms. Just use bind to attach the function to async_wait and call expires_from_now .
io_service io;
deadline_timer timer(io);
void handler()
{
static int second_counter = 0;
cout << second_counter++ << endl;
timer.expires_from_now(posix_time::seconds(1));
timer.async_wait(bind(&handler));
}
int main(int argc, char* argv[])
{
handler();
io.run();
}
It will take a little time to get into Asia (especially because the documentation is ... patchy), but it's worth learning.
source to share
In Cocoa, a typical call looks like this:
NSTimer *repeatingTimer= [NSTimer scheduledTimerWithTimeInterval:timeIntervalInSecs target:objectImplementingFunction selector:@selector(nameOfYourFunction:) userInfo:argToYourFunction repeats:YES];
which causes the timer to be placed in the current runloop. Whenever the timer fires, it calls your function.
If you later want to cancel the timer call
[repeatingTimer invalidate];
which removes it from runloop.
source to share
I have a small tutorial on my page
http://cocoa-coding.de/timer/nstimer.html
This is in German only, but I'm sure you will understand the code samples.
source to share