Execute a method every x seconds in C

后端 未结 4 998
别那么骄傲
别那么骄傲 2021-01-06 00:29

Is there an example of a working timer that executes some function every x amount seconds using C.

I\'d appreciate an example working code.

4条回答
  •  孤城傲影
    2021-01-06 00:34

    IMO, in this case, you can utilize gettimeofday() into algorithm like: use such a while(1) that counts time difference between current time and last_execution_time, everytime the difference reach 1 seconds, update the last_execution_time and call the function that supposed to run in every 1 second.

    #include 
    #include 
    
    #DEFINE DESIRED_INTERVAL 1  //1 second
    int get_tv_cur_minus_given(struct timeval *tv, struct timeval *tp_given, int *sign)
    {
        struct timeval tp_cur;
    
    
        gettimeofday(&tp_cur,NULL);
    
        tv->tv_sec  = tp_cur.tv_sec - tp_given->tv_sec;
        tv->tv_usec = tp_cur.tv_usec - tp_given->tv_usec;
    
        if(tv->tv_sec > 0) {
            *sign = 1;
            if(tv->tv_usec < 0) {
                tv->tv_sec--;
                tv->tv_usec = 1000000 + tv->tv_usec;
            }
        }else
        if(tv->tv_sec == 0) {
            if(tv->tv_usec == 0)
                *sign = 0;
            else
            if(tv->tv_usec < 0) {
                *sign = -1;
                tv->tv_usec *= -1;
            }else
                *sign = 1;
        }else {
            *sign = -1;
            if(tv->tv_usec > 0) {
                tv->tv_sec++;
                tv->tv_usec = 1000000 - tv->tv_usec;
            }else
            if(tv->tv_usec < 0)
                tv->tv_usec *= -1;
        return 0;
            }
    }
    
    int main()
    {
        struct timeval      tv_last_run;
        struct timeval  tv_diff;
        int sign;
    
    
        while(true)
        {
    
         get_tv_cur_minus_given(&tv_diff, &tv_last_run, &sign);
    
            if(tv_diff.tv_sec > DESIRED_INTERVAL)
            {
                gettimeofday(&tv_last_run,NULL);
                printf("\ncall the func here");
            }
        }
    
        return 0;
    }
    

    In case you need different thread out of main thread, move the lines inside main() into a function pointer and pass it through pthread_create function, eg :

    void *threadproc(void *arg)
    {
       while(1)
       {
           //put the same lines as inside main() function in above code snippet. .
       }
    }
    pthread_create(&tid, NULL, &threadproc, NULL);
    

提交回复
热议问题