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.
You could spawn a new thread:
void *threadproc(void *arg)
{
while(!done)
{
sleep(delay_in_seconds);
call_function();
}
return 0;
}
...
pthread_t tid;
pthread_create(&tid, NULL, &threadproc, NULL);
Or, you could set an alarm with alarm(2)
or setitimer(2)
:
void on_alarm(int signum)
{
call_function();
if(!done)
alarm(delay_in_seconds); // Reschedule alarm
}
...
// Setup on_alarm as a signal handler for the SIGALRM signal
struct sigaction act;
act.sa_handler = &on_alarm;
act.sa_mask = 0;
act.sa_flags = SA_RESTART; // Restart interrupted system calls
sigaction(SIGALRM, &act, NULL);
alarm(delay_in_seconds); // Setup initial alarm
Of course, both of these methods have the problem that the function you're calling periodically needs to be thread-safe.
The signal method is particularly dangerous because it must also be async-safe, which is very hard to do -- even something as simple as printf
is unsafe because printf
might allocate memory, and if the SIGALRM
interrupted a call to malloc
, you're in trouble because malloc
is not reentrant. So I wouldn't recommend the signal method, unless all you do is set a flag in the signal handler which later gets checked by some other function, which puts you back in the same place as the threaded version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With