Question

I want to register handler for the following event: "system clock timer incremented second counter". Is it possible to attach handler for this event? In the other words I want to call an appropriate function every second. It seems that the following solution is very bad:

#include <ctime>

bool checkTimer(int sec_now)
{
    time_t t= time(0);
    int sec=localtime(&t)->tm_sec;
    if(sec_now!=sec)
        return true;
    return false;
}

void callback()
{
    //handler
}

int main()
{
    while(true)
    {
        time_t t= time(0);
        int sec_now=localtime(&t)->tm_sec;
        while(!checkTimer(sec_now)){ }
        callback();
    }
}

This code works as I want. But I think that it is bad way. Can you propose another way to do this? I'm using linux mint 14.

Was it helpful?

Solution

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top