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

前端 未结 5 1649
离开以前
离开以前 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 <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;
    }
    
    0 讨论(0)
  • 2021-01-22 12:23

    Simple:

    #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 讨论(0)
  • 2021-01-22 12:30

    Try this:

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

    This is in Java-Syntax, i didn't program c since more than 5 years, but maybe it helps you :)

    0 讨论(0)
  • 2021-01-22 12:35

    Most operating systems have a way to "set an alarm" or "set a timer", which will call a function of yours at a given time in the future. In linux, you'd use alarm, in Windows you'd use SetTimer.

    These functions have restrictions on what you can do in the function that gets called, and you almost certainly will end up with something that has multiple threads in the end anyway - although the thread may not be calling sleep, but some wait_for_event or similar function instead.

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

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

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

    0 讨论(0)
  • 2021-01-22 12:39

    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 might want a flag that tells if the function has been called, or it will be called several times during the single second (diff % 10) == 0 is true.

    0 讨论(0)
提交回复
热议问题