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.

+2


source to share


6 answers


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.

+1


source


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.

+4


source


Take a look at the NSTimer class.

+2


source


If you want simplicity that you just don't use alarm()

?

Set a signal handler for SIGALRM

and then call alarm()

to ask the OS to emit a signal after the delay. Here's an example here .

+1


source


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.

0


source


Poco C ++ library provides a cross platform Timer class .

0


source







All Articles