From 12da91b9cac6bc0cecbf8ef4919df160b4d21e21 Mon Sep 17 00:00:00 2001 From: Vaxry Date: Tue, 20 Feb 2024 00:59:35 +0000 Subject: [PATCH] Timer: add --- src/core/Timer.cpp | 25 +++++++++++++++++++++++++ src/core/Timer.hpp | 23 +++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 src/core/Timer.cpp create mode 100644 src/core/Timer.hpp diff --git a/src/core/Timer.cpp b/src/core/Timer.cpp new file mode 100644 index 0000000..f682bde --- /dev/null +++ b/src/core/Timer.cpp @@ -0,0 +1,25 @@ +#include "Timer.hpp" + +CTimer::CTimer(std::chrono::system_clock::duration timeout, std::function self, void* data)> cb_, void* data_) : cb(cb_), data(data_) { + expires = std::chrono::system_clock::now() + timeout; +} + +bool CTimer::passed() { + return std::chrono::system_clock::now() > expires; +} + +void CTimer::cancel() { + wasCancelled = true; +} + +bool CTimer::cancelled() { + return wasCancelled; +} + +void CTimer::call(std::shared_ptr self) { + cb(self, data); +} + +float CTimer::leftMs() { + return std::chrono::duration_cast(expires - std::chrono::system_clock::now()).count(); +} \ No newline at end of file diff --git a/src/core/Timer.hpp b/src/core/Timer.hpp new file mode 100644 index 0000000..3028674 --- /dev/null +++ b/src/core/Timer.hpp @@ -0,0 +1,23 @@ +#pragma once + +#include +#include + +class CTimer { + public: + CTimer(std::chrono::system_clock::duration timeout, std::function self, void* data)> cb_, void* data_); + + void cancel(); + bool passed(); + + float leftMs(); + + bool cancelled(); + void call(std::shared_ptr self); + + private: + std::function self, void* data)> cb; + void* data = nullptr; + std::chrono::system_clock::time_point expires; + bool wasCancelled = false; +}; \ No newline at end of file