72 lines
1.2 KiB
C++
72 lines
1.2 KiB
C++
|
#include <time.h>
|
||
|
|
||
|
#include "timerservice.h"
|
||
|
|
||
|
Timer::Timer(Command* cmd, unsigned int timeval)
|
||
|
: next(0), cmd(cmd), timeval(timeval)
|
||
|
{
|
||
|
}
|
||
|
|
||
|
Timer::~Timer()
|
||
|
{
|
||
|
delete cmd;
|
||
|
}
|
||
|
|
||
|
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->cmd->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();
|
||
|
}
|