views:

2708

answers:

5
+1  Q: 

C Timer Callback

Interested in something similar to JavaScript setTimeout in C on both UNIX and Windows.

Basically, I want:

start_timer(&function_pointer, int time_in_secs)

or as close to that as I can get.

Also, something similar to setInterval would be nice (where it calls the callback every n seconds), but that can be implemented using setTimeout :)

+2  A: 

For UNIX, man setitimer.

Employed Russian
A: 

Try glib. If you need portable code, there's high probability that you cannot write anything more portable than them ;)

http://library.gnome.org/devel/glib/2.20/glib-The-Main-Event-Loop.html#g-timeout-add

viraptor
+1  A: 

Some information about alarm() and setitimer() can be found here. Note that the upcall function is a signal handler, so it is subject to all of the limitations and restrictions associated with signal handlers as described in great detail here.

As noted in the first link, alarm() is POSIX-based, setitimer() is not (although it is more flexible).

Lance Richardson
The current POSIX spec says setitimer() and getitimer() are obsolescent and may be removed in a future edition. The recommended replacements are timer_gettime() and timer_settime().
Jonathan Leffler
@Jonathan, you're right, it looks like the glibc doc is incorrect (or at least misleading) regarding setitimer()/getitimer() being non-POSIX interfaces. Is something newer than the 2004 version of 1003.1 available online? The best I could find was here: http://www.unix.org/single_unix_specification/.
Lance Richardson
The Open Group Base Specifications Issue 7IEEE Std 1003.1™-2008 at http://www.opengroup.org/onlinepubs/9699919799/toc.htm
Jonathan Leffler
+1  A: 

SetTimer in Win32 with a TimerProc as the call back.

/* calls TimerProc once every 60000 milliseconds */
SetTimer(NULL, 1, 60000, TimerProc);
scottm
+4  A: 

You might want to try the POSIX interval timers, timer_create and timer_settime, as it allows you to specify a call back function directly without using signals. To get the timer to expire just once ( and not keep repeating ):

timer_settime: The reload value of the timer shall be set to the value specified by the it_interval member of value. When a timer is armed with a non-zero it_interval, a periodic (or repetitive) timer is specified.

Here is extensive documentation of using these timers with a nice example from the Linux Programmer's Manual on kernel.org:

timer_create - create a POSIX per-process timer

Robert S. Barnes