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

前端 未结 5 1652
离开以前
离开以前 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: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.

提交回复
热议问题