Run method every x seconds in C

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

I would appreciate an example of working code.

+4
source share
2 answers

You can create a new thread:

void *threadproc(void *arg) { while(!done) { sleep(delay_in_seconds); call_function(); } return 0; } ... pthread_t tid; pthread_create(&tid, NULL, &threadproc, NULL); 

Or you can set an alarm with alarm(2) or setitimer(2) :

 void on_alarm(int signum) { call_function(); if(!done) alarm(delay_in_seconds); // Reschedule alarm } ... // Setup on_alarm as a signal handler for the SIGALRM signal struct sigaction act; act.sa_handler = &on_alarm; act.sa_mask = 0; act.sa_flags = SA_RESTART; // Restart interrupted system calls sigaction(SIGALRM, &act, NULL); alarm(delay_in_seconds); // Setup initial alarm 

Of course, both of these methods have a problem that the function you call periodically must be thread safe.

The signal method is especially dangerous, since it must also be asynchronous, which is very difficult to do - even that which is simply printf insecure because printf can allocate memory, and if SIGALRM interrupted the call to malloc , you have problems because malloc not repeated. Therefore, I would not recommend a signal method, unless you select the checkbox in the signal handler, which is later checked by some other function that returns you to the same place as the streaming version.

+10
source

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

Using POSIX Timers

The POSIX timer_create function creates a timer that can be configured to deliver a one-time or periodic notification when the timer expires. When creating a timer, you can request delivery by signal or in a new stream. Since using the signals correctly is difficult (there are strict rules about what you can and cannot do from the signal handler, and breaking the rules often β€œseems to work” until you're lucky), I would recommend using stream delivery .

Scrolling your own timer using a thread

It really is as simple as it sounds. Create a new thread that goes into the loop, and do whatever you need each time the required time is up.

+4
source

All Articles