You can create 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 can 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 a problem that the function you call periodically must be thread safe.
The signal method is especially dangerous, since it must also be asynchronous, which is very difficult to do - even that which is simply printf insecure because printf can allocate memory, and if SIGALRM interrupted the call to malloc , you have problems because malloc not repeated. Therefore, I would not recommend a signal method, unless you select the checkbox in the signal handler, which is later checked by some other function that returns you to the same place as the streaming version.
source share