EventManager: add support for timers

This commit is contained in:
Maxime Coste 2013-01-14 19:07:38 +01:00
parent eaaf88db1d
commit 90eeb7b8a7
2 changed files with 51 additions and 0 deletions

View File

@ -16,6 +16,23 @@ FDWatcher::~FDWatcher()
EventManager::instance().m_fd_watchers.remove(this); EventManager::instance().m_fd_watchers.remove(this);
} }
Timer::Timer(TimePoint date, Callback callback)
: m_date{date}, m_callback{std::move(callback)}
{
EventManager::instance().m_timers.add(this);
}
Timer::~Timer()
{
EventManager::instance().m_timers.remove(this);
}
void Timer::run()
{
m_date = TimePoint::max();
m_callback(*this);
}
EventManager::EventManager() EventManager::EventManager()
{ {
m_forced_fd.reserve(4); m_forced_fd.reserve(4);
@ -24,6 +41,7 @@ EventManager::EventManager()
EventManager::~EventManager() EventManager::~EventManager()
{ {
assert(m_fd_watchers.empty()); assert(m_fd_watchers.empty());
assert(m_timers.empty());
} }
void EventManager::handle_next_events() void EventManager::handle_next_events()
@ -48,6 +66,13 @@ void EventManager::handle_next_events()
(*it)->run(); (*it)->run();
} }
} }
TimePoint now = Clock::now();
for (auto& timer : m_timers)
{
if (timer->next_date() <= now)
timer->run();
}
} }
void EventManager::force_signal(int fd) void EventManager::force_signal(int fd)

View File

@ -3,6 +3,8 @@
#include "utils.hh" #include "utils.hh"
#include <chrono>
namespace Kakoune namespace Kakoune
{ {
@ -20,6 +22,26 @@ private:
Callback m_callback; Callback m_callback;
}; };
using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;
class Timer
{
public:
using Callback = std::function<void (Timer& timer)>;
Timer(TimePoint date, Callback callback);
~Timer();
TimePoint next_date() const { return m_date; }
void set_next_date(TimePoint date) { m_date = date; }
void run();
private:
TimePoint m_date;
Callback m_callback;
};
// The EventManager provides an interface to file descriptor // The EventManager provides an interface to file descriptor
// based event handling. // based event handling.
// //
@ -39,8 +61,12 @@ public:
private: private:
friend class FDWatcher; friend class FDWatcher;
friend class Timer;
Set<FDWatcher*> m_fd_watchers; Set<FDWatcher*> m_fd_watchers;
Set<Timer*> m_timers;
std::vector<int> m_forced_fd; std::vector<int> m_forced_fd;
TimePoint m_last;
}; };
} }