I want to call a function, let’s say every 10 or 20 seconds. When I searched, I came up with threads and the sleep() method everywhere.
I also checked for time and clock classes in C, but I could not find anything helpful specific to my question.
What is the simplest way to call functions periodically?
Using libevent, in my opinion, is the cleaner solution because, in the meantime, you can do other operations (even other timed functions).
Look at this simple and self-explanatory example that print out Hello every three 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With