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

前端 未结 5 1650
离开以前
离开以前 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题