Call a function periodically without using threads and the sleep () method in c

I want to call a function, say every 10 or 20 seconds. When I searched, I came up with themes and the sleep() method everywhere.

I also checked the time and clock classes in C, but I could not find anything useful for my question.

What is the easiest way to periodically call functions?

+2
source share
5 answers

Use libevent , in my opinion, this is a cleaner solution, because you can perform other operations (even other functions of time)

look at this simple and self explanatory example that prints Hello every 3 seconds:

 #include <stdio.h> #include <sys/time.h> #include <event.h> void say_hello(int fd, short event, void *arg) { printf("Hello\n"); } int main(int argc, const char* argv[]) { struct event ev; struct timeval tv; tv.tv_sec = 3; tv.tv_usec = 0; event_init(); evtimer_set(&ev, say_hello, NULL); evtimer_add(&ev, &tv); event_dispatch(); return 0; } 
+4
source

Most operating systems have a way to "set an alarm" or "set a timer", which in the future will call the function of your user. In linux you would use alarm , in Windows you would use SetTimer .

These functions have limitations on what you can do in the called function, and you will almost certainly end up having multiple threads, although the thread may not call sleep , but some wait_for_event or a similar function.

Edit: However, using a stream with a stream that contains:

 while(1) { sleep(required_time); function(); } 

The problem is solved in a very direct way to solve the problem and makes it very easy to handle.

+4
source

A naive solution would be something like this:

 /* Infinite loop */ time_t start_time = time(NULL); for (;;) { time_t now = time(NULL); time_t diff = now - start_time; if ((diff % 10) == 0) { /* Ten seconds has passed */ } if ((diff % 20) == 0) { /* Twenty seconds has passed */ } } 

You may need a flag that indicates whether the function was called, or if it will be called several times in one second. (diff % 10) == 0 - true.

+1
source

Try the following:

 while(true) { if(System.getNanotime % 20 == 0) { myFunction(); } } 

This is in Java syntax, I have not programmed c for more than 5 years, but maybe this will help you :)

+1
source

Plain:

 #include <stdio.h> #include <unistd.h> int main(int argc, const char** argv) { while(1) { usleep(20000) ; printf("tick!\n") ; } } 

Note that usleep () will, of course, block :)

0
source

All Articles