Tickers in C
Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
volatile int should_continue = 1;
void* ticker_func(void* arg) {
while (should_continue) {
time_t now = time(NULL);
char* time_str = ctime(&now);
time_str[strlen(time_str) - 1] = '\0'; // Remove newline
printf("Tick at %s\n", time_str);
usleep(500000); // Sleep for 500 milliseconds
}
return NULL;
}
int main() {
pthread_t ticker_thread;
// Create a thread to simulate the ticker
if (pthread_create(&ticker_thread, NULL, ticker_func, NULL) != 0) {
fprintf(stderr, "Failed to create thread\n");
return 1;
}
// Let the ticker run for about 1600 milliseconds
usleep(1600000);
// Stop the ticker
should_continue = 0;
// Wait for the ticker thread to finish
pthread_join(ticker_thread, NULL);
printf("Ticker stopped\n");
return 0;
}
In this C implementation, we use POSIX threads to simulate the ticker functionality. The ticker_func
runs in a separate thread and prints the current time every 500 milliseconds.
We use a volatile boolean variable should_continue
to control the ticker. The main thread sleeps for 1600 milliseconds, then sets should_continue
to false, effectively stopping the ticker.
To compile and run this program:
$ gcc -o tickers tickers.c -lpthread
$ ./tickers
Tick at Sun Jun 18 15:30:45 2023
Tick at Sun Jun 18 15:30:46 2023
Tick at Sun Jun 18 15:30:46 2023
Ticker stopped
When we run this program, the ticker should tick about 3 times before we stop it. The exact number of ticks may vary slightly due to system scheduling.
Note that this C implementation is a simplified version of the concept. Unlike Go’s built-in ticker, this version doesn’t guarantee exact timing intervals and doesn’t provide a way to reset or adjust the ticker while it’s running. For more precise timing in C, you might want to look into system-specific timer APIs.