The generic approach is to write an infinite loop (while (1) { ... }
) and pause your program execution each tick.
To pause, you may use sleep
function from standard library. Alternatively to sleep
, which can only specify sleeping time in seconds, you can use nanosleep
function that allows better precision.
#include <stdio.h>
#include <time.h>
int main()
{
struct timespec t = { 3/*seconds*/, 0/*nanoseconds*/};
while (1){
printf("Wait three seconds and...\n");
nanosleep(&t,NULL);
fflush(stdout); //see below
}
}
Note that unless you add a newline character (\n
) to the string you outpu, you most likely will see nothing, because the string is first printed to a buffer and that buffer is occasionally flushed to the terminal (that usually happens when you print a newline, but even this cannot guarantee the flush on every system). That's why it's better to add fflush
call.