src/Timer.cc
author nireco
Sat, 31 Jan 2009 12:33:08 +0200
changeset 443 5d1119729f58
parent 423 947ab54de4b7
permissions -rw-r--r--
worm02 two pics to comment

#include "Timer.hh"

Timer::Timer (TimeMS interval) :
    interval(interval), 
    ticks(0), 
    enabled(false),
    last_tick(0)
{

}

TickCount Timer::get_ticks (void) {
    return ticks;
}

void Timer::start (void) {
    last_tick = CL_System::get_time();

    enabled = true;
    single_shot = false;
}
        
void Timer::fire_once (void) {
    last_tick = CL_System::get_time();

    enabled = true;
    single_shot = true;
}

void Timer::keep_alive (void) {
    // ignore if disabled
    if (!enabled)
        return;

    // get current time
    TimeMS now = CL_System::get_time();

    // handle overflows
    if (last_tick > now)
        last_tick = now;
    
    // is the tick over?
    if (last_tick + interval < now) {
        // the length of this tick
        TimeMS tick_length = now - last_tick;
        
        // trigger our signal
        _sig_tick(tick_length);
        
        // update state
        last_tick = now;

        // XXX: handle overflow
        ticks += (TickCount) tick_length / interval;

        // if it was single-shot, disable
        if (single_shot)
            enabled = false;
    }
}