Call a function in the future

In a long-term server program (embedded in C) in a Posix (Linux) environment: what's the best way to get a function to execute at a specific time in the future ? It does not need to be executed on any particular thread, but the accuracy of the execution time should be a few milliseconds. Generic approaches or specific code are appreciated.

+4
source share
2 answers

The GNU C library ( sys/timex.h ) has some high-resolution clock functions, so although they are not POSIX, they will be portable Linux.

High Precision Clock - GNU C Library

These functions are prefixed with 'ntp', although they do not require or use any ntp service, therefore the relation is purely superficial.

Remember that although the grain size is in microseconds, the linux kernel has a delay in user space of 10 ms, so do not worry and do not expect anything more accurate.

Once you have the current high resolution, you can calculate the duration and use ( posix ) nanosleep (but again, round up to 10 ms) to set the delay. There is also clock_nanosleep , which may be of interest.

+1
source

You should watch posix timers. This gives you a simple interface for planning your future work. You can control it to send you a signal in x seconds / nanoseconds (and then you can put your function as a signal handler). Lookup timer_create

0
source

All Articles