#include #include "timerservice.h" // TODO: how to deregister TimerEvents? Timer::Timer(Event* event, unsigned int timeval) : next(0), event(event), timeval(timeval) { } Timer::~Timer() { delete event; } TimerService::~TimerService() { Timer* search = firstTimer; while (search != NULL) { Timer* next = search->next; delete search; search = next; } } void TimerService::addTimer(Timer* te, bool trigger) { te->timeout = time(NULL) + ((!trigger) ? te->timeval : 0); Timer** search = &firstTimer; while ((*search) != NULL && (*search)->timeout <= te->timeout) search = &((*search)->next); te->next = (*search); (*search) = te; } void TimerService::checkTimeouts() { long now = time(NULL); Timer* search = firstTimer; while (search != NULL && search->timeout <= now) { search->event->execute(); firstTimer = search->next; addTimer(search, false); search = firstTimer; } } TimerService* TimerService::getInstance() { static TimerService ts; return &ts; } void TimerService::registerTimer(Timer* te) { TimerService* ts = getInstance(); AutoMutex am(ts->mutex); ts->addTimer(te, true); } void TimerService::checkTimers() { TimerService* ts = getInstance(); AutoMutex am(ts->mutex); ts->checkTimeouts(); }