This code works as I want. But I think that it is bad way.
The problem with this implementation is that the program is busy looping: it consumes all the CPU time on one core. There are several ways to implement an interval timer on Linux. For instance, you can have a look at timerfd.
#include <iostream>
#include <inttypes.h>
#include <sys/timerfd.h>
#include <unistd.h>
void callback(void)
{
std::cout << "callback()" << std::endl;
}
int main(void)
{
int tfd;
uint64_t count;
// Interval timer that expires every 1 second
struct itimerspec timer = {
.it_interval = {1, 0}, // interval for periodic timer
.it_value = {1, 0}, // initial expiration
};
tfd = timerfd_create(CLOCK_MONOTONIC, 0);
timerfd_settime(tfd, 0, &timer, NULL);
while (true) {
read(tfd, &count, sizeof(count));
callback();
}
close(tfd);
return 0;
}