feat: EventThrottler

This commit is contained in:
Michael Carlberg 2016-06-21 04:16:55 +02:00
parent c506829e4e
commit ac22b59a40
3 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,31 @@
#pragma once
#include <chrono>
#include <deque>
#include <memory>
#include <string>
namespace event_throttler
{
typedef std::chrono::duration<double, std::milli> timewindow_t;
typedef std::chrono::high_resolution_clock timepoint_clock_t;
typedef event_throttler::timepoint_clock_t::time_point timepoint_t;
typedef std::deque<event_throttler::timepoint_t> queue_t;
typedef std::size_t limit_t;
}
class EventThrottler
{
event_throttler::queue_t event_queue;
event_throttler::limit_t passthrough_limit;
event_throttler::timewindow_t timewindow;
protected:
void expire();
public:
explicit EventThrottler(int limit, event_throttler::timewindow_t timewindow)
: passthrough_limit(limit), timewindow(timewindow) {}
bool passthrough();
};

View File

@ -43,6 +43,7 @@ set(SOURCE_FILES
"src/modules/text.cpp"
"src/services/builder.cpp"
"src/services/command.cpp"
"src/services/event_throttler.cpp"
"src/services/inotify.cpp"
"src/services/logger.cpp"
# "src/services/store.cpp"

View File

@ -0,0 +1,40 @@
#include <thread>
#include "services/event_throttler.hpp"
#include "services/logger.hpp"
using namespace event_throttler;
bool EventThrottler::passthrough()
{
// Remove expired frames from the queue
this->expire();
// Place the new frame in the bottom of the deck
this->event_queue.emplace_back(timepoint_clock_t::now());
// Check if the limit has been reached
if (this->event_queue.size() >= this->passthrough_limit) {
// std::this_thread::sleep_for(this->timewindow * this->event_queue.size());
std::this_thread::sleep_for(this->timewindow);
if (this->event_queue.size() - 1 >= this->passthrough_limit) {
log_trace("Event passthrough throttled");
return false;
}
}
return true;
}
void EventThrottler::expire()
{
auto now = timepoint_clock_t::now();
while (this->event_queue.size() > 0) {
if ((now - this->event_queue.front()) < this->timewindow)
break;
this->event_queue.pop_front();
}
}