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
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;
}
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 :)
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 :)
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.
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.