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
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.