Search code examples
c

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


I want to call a function, lets say every 10 or 20 seconds. When I searched, I came up with threads and 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 most simple way to call functions periodically?


Solution

  • Use 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 explaining example that print out 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;
    }