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

前端 未结 5 1648
离开以前
离开以前 2021-01-22 11:53

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

5条回答
  •  一生所求
    2021-01-22 12:23

    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 
    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题