diff --git a/external/CMakeLists.txt b/external/CMakeLists.txt index 1439e8c..33a8a82 100644 --- a/external/CMakeLists.txt +++ b/external/CMakeLists.txt @@ -1 +1,2 @@ -add_subdirectory(color) \ No newline at end of file +add_subdirectory(color) +add_subdirectory(timer) \ No newline at end of file diff --git a/external/timer/CMakeLists.txt b/external/timer/CMakeLists.txt new file mode 100644 index 0000000..a7fc476 --- /dev/null +++ b/external/timer/CMakeLists.txt @@ -0,0 +1,12 @@ +add_library(Timer STATIC) + +target_sources(Timer + PRIVATE + ${CMAKE_CURRENT_LIST_DIR}/timer.cpp + +) + +target_include_directories(Timer + PUBLIC + ${CMAKE_CURRENT_LIST_DIR} +) \ No newline at end of file diff --git a/external/timer/timer.cpp b/external/timer/timer.cpp new file mode 100644 index 0000000..f38d10f --- /dev/null +++ b/external/timer/timer.cpp @@ -0,0 +1,34 @@ +#include "timer.hpp" + +Timer::Timer(void (*function)()) { + this->function = function; +} + +void Timer::setTimeout(std::chrono::milliseconds delay) { + + this->p_clear = false; + std::thread t([this, delay]() { + if(this->p_clear) return; + std::this_thread::sleep_for(delay); + if(this->p_clear) return; + function(); + }); + t.detach(); +} + +void Timer::setInterval(std::chrono::milliseconds interval) { + this->p_clear = false; + std::thread t([this, interval]() { + while(true) { + if(this->p_clear) return; + std::this_thread::sleep_for(interval); + if(this->p_clear) return; + function(); + } + }); + t.detach(); +} + +void Timer::stop() { + this->p_clear = true; +} \ No newline at end of file diff --git a/external/timer/timer.hpp b/external/timer/timer.hpp new file mode 100644 index 0000000..7c44605 --- /dev/null +++ b/external/timer/timer.hpp @@ -0,0 +1,15 @@ +#pragma once +#include +#include + +class Timer { +public: + Timer(void (*function)()); + void setTimeout(std::chrono::milliseconds delay); + void setInterval(std::chrono::milliseconds interval); + void stop(); +private: + bool p_clear = false; + std::mutex p_clear_mutex; + void (*function)(); +}; \ No newline at end of file