#pragma once
#include <chrono>
#include <memory>
#include <thread>
#include <functional>
class Timer {
public:
Timer() : stop(false), interval(1000) {}
Timer(const int& interval) : stop(false), interval(interval) {}
Timer(std::function<void()> do_update) : do_update(do_update), stop(false), interval(1000) {}
Timer(const int& interval, std::function<void()> do_update) : interval(interval), do_update(do_update), stop(false) {};
void Start() {
stop = false;
if(timer_t == nullptr) {
timer_t = std::make_unique<std::thread>(std::thread([&]() {
while(not stop) {
do_update();
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
}
}));
timer_t->detach();
}
}
void Stop() { stop = true; }
void SetInterval(int value) {
interval = value;
}
int GetInterval() {
return interval;
}
void SetDoUpdate(std::function<void()> value) {
do_update = value;
}
private:
std::function<void()> do_update;
int interval;
bool stop;
std::unique_ptr<std::thread> timer_t = nullptr;
};