tags:

views:

167

answers:

6

Is there any equivalent function on OS X to SetTimer in Windows? I'm using C++.

So I'm writing a plugin for some software, and I need to have a funtion called periodically. On Windows I just pass the address of the function to SetTimer() and it will be called at a given interval. Is there an easy way to do this on OS X? It should be as minimalistic as possible. I didn't really find anything nonfancy on the web, there was something about a huge framework and another solution using a second thread that is sleeping the other time, but I think there should be an easier way.

+2  A: 

Have a look at the NSTimer class.

Abizern
A: 

I have a little tutorial on my page

http://cocoa-coding.de/timer/nstimer.html

It's only in German but I am sure you will understand the code samples.

Holli
A: 

If you want simplicity, which don't you just use alarm()?

Set a signal handler for SIGALRM, and then call alarm() to ask the OS to generate the signal after a delay. There's an example here.

alex tingle
A: 

Consider using the Boost Asio library. The class deadline_timer works on all platforms. Just use bind to attach a 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'll take a little time to get your head around Asio (especially since the documentation is...patchy) but it's well worth learning.

MattyT
Hmm, don't quite understand the 0 rating (though I'm grateful the answer was accepted!)? The author explicitly mentioned they were using C++ (not Cocoa, like some of the answers assumed) and this is the best way I know of to set a timer in that language...
MattyT
+4  A: 

In Cocoa, a typical call goes something like this;

NSTimer *repeatingTimer=  [NSTimer scheduledTimerWithTimeInterval:timeIntervalInSecs target:objectImplementingFunction selector:@selector(nameOfYourFunction:) userInfo:argToYourFunction repeats:YES];

which causes a timer to be placed on the current runloop. Whenever the timer fires it will call your function.

If you later want to cancel the timer call

[repeatingTimer invalidate];

which removes it from the runloop.

Ira Cooke
A: 

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

StackedCrooked