Browse Source

timer_handle design fix, fix scheduler, comments

master
Odilitime 4 years ago
parent
commit
57af0f9f81
2 changed files with 15 additions and 8 deletions
  1. 12
    6
      src/scheduler.cpp
  2. 3
    2
      src/scheduler.h

+ 12
- 6
src/scheduler.cpp View File

@@ -8,7 +8,8 @@ std::shared_ptr<timer_handle> Scheduler::setTimeout(std::function<void()> callba
std::shared_ptr<timer_handle> handle = std::make_shared<timer_handle>();
handle->callback = callback;
handle->nextAt = now + delay;
handle->timeout = true;
handle->interval = 0;
//handle->timeout = true;
this->timers.push_back(handle);
return handle;
}
@@ -19,7 +20,8 @@ std::shared_ptr<timer_handle> Scheduler::setInterval(std::function<void()> callb
std::shared_ptr<timer_handle> handle = std::make_shared<timer_handle>();
handle->callback = callback;
handle->nextAt = now + delay;
handle->timeout = false;
handle->interval = delay;
//handle->timeout = false;
this->timers.push_back(handle);
//std::cout << "scheduled at " << (int)handle->nextAt << std::endl;
return handle;
@@ -31,8 +33,8 @@ unsigned long Scheduler::getNext() {
//std::cout << "there are " << this->timers.size() << std::endl;
for(std::vector<std::shared_ptr<timer_handle>>::iterator it=this->timers.begin(); it!=this->timers.end(); ++it) {
//std::cout << "nextAt " << (int)it->get()->nextAt << " long " << (int)(now - it->get()->nextAt) << std::endl;
//std::cout << "now " << (int)now << " nextAt: " << (int)it->get()->nextAt << std::endl;
int diff = now - it->get()->nextAt;
//std::cout << "now " << (int)now << " - nextAt: " << (int)it->get()->nextAt << std::endl;
int diff = it->get()->nextAt - now;
if (diff < 0) diff = 0;
//std::cout << "timer fires in " << diff << std::endl;
lowest = std::min(lowest, static_cast<unsigned long>(diff));
@@ -43,19 +45,23 @@ unsigned long Scheduler::getNext() {

bool Scheduler::fireTimer(std::shared_ptr<timer_handle> timer, double now) {
timer->callback();
if (timer->timeout) {
if (!timer->interval) {
return true;
}
// schedule the next one
timer->nextAt = now + timer->nextAt;
//std::cout << "Scheduling next timer in " << timer->interval << "+" << now << "=" << (now + timer->interval) << std::endl;
timer->nextAt = now + timer->interval;
return false;
}

void Scheduler::fireTimers() {
double now = glfwGetTime() * 1000;
for(std::vector<std::shared_ptr<timer_handle>>::iterator it=this->timers.begin(); it!=this->timers.end(); ++it) {
// if it's the timer time to fire
if (it->get()->nextAt < now) {
// fire it, do we need to clean it up
if (this->fireTimer(*it, now)) {
// clena up
it = this->timers.erase(it);
if (it == this->timers.end()) break;
}

+ 3
- 2
src/scheduler.h View File

@@ -8,8 +8,9 @@

class timer_handle {
public:
double nextAt; // in milliseconds
bool timeout;
unsigned long interval; // in milliseconds
double nextAt; // timestamp in milliseconds
//bool timeout; // replaced by interval
std::function<void()> callback;
};


Loading…
Cancel
Save