Execute a method every x seconds in C

后端 未结 4 1025
别那么骄傲
别那么骄傲 2021-01-06 00:29

Is there an example of a working timer that executes some function every x amount seconds using C.

I\'d appreciate an example working code.

4条回答
  •  [愿得一人]
    2021-01-06 00:35

    There are various legacy ways to do this using interval timers and signals, but I'm going to present two modern approaches:

    Using POSIX timers

    The POSIX timer_create function creates a timer that can be configured to deliver a one-off or periodic notification when the timer expires. When creating the timer, you can request either delivery via a signal or in a new thread. Since using signals correctly is complicated (there are strict rules about what you can and cannot do from a signal handler, and breaking the rules often "seems to work" until you get unlucky), I would recommend using thread-based delivery.

    Rolling your own timer with a thread

    This is really as easy as it sounds. Make a new thread that goes into a loop sleeping and doing whatever you need done every time the desired time has elapsed.

提交回复
热议问题