Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 881
gozde baris Avatar asked Jul 17 '26 14:07

gozde baris


1 Answers

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;
}
like image 146
Davide Berra Avatar answered Jul 20 '26 09:07

Davide Berra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!