| 1 |
#pragma once |
| 2 |
#include <thread> |
| 3 |
#include <atomic> |
| 4 |
#include <functional> |
| 5 |
#include <LibLsp/lsp/asio.h> |
| 6 |
|
| 7 |
template<typename Duration = std::chrono::milliseconds> |
| 8 |
class SimpleTimer |
| 9 |
{ |
| 10 |
public: |
| 11 |
SimpleTimer(unsigned int duration, std::function<void()> const& _call_back) |
| 12 |
: is_running_(true), call_back(_call_back), _timer(_ios, Duration(duration)) |
| 13 |
{ |
| 14 |
_timer.async_wait( |
| 15 |
[&](std::error_code const& e) |
| 16 |
{ |
| 17 |
if (e.value() == asio::error::operation_aborted) |
| 18 |
{ |
| 19 |
return; |
| 20 |
} |
| 21 |
if (is_running_.load(std::memory_order_relaxed)) |
| 22 |
{ |
| 23 |
call_back(); |
| 24 |
} |
| 25 |
} |
| 26 |
); |
| 27 |
_thread = std::thread([this] { _ios.run(); }); |
| 28 |
} |
| 29 |
~SimpleTimer() |
| 30 |
{ |
| 31 |
Stop(); |
| 32 |
} |
| 33 |
void Stop() |
| 34 |
{ |
| 35 |
is_running_.store(false, std::memory_order_relaxed); |
| 36 |
_ios.stop(); |
| 37 |
if (_thread.joinable()) |
| 38 |
{ |
| 39 |
_thread.join(); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
private: |
| 44 |
std::atomic_bool is_running_; |
| 45 |
std::function<void()> call_back; |
| 46 |
asio::io_context _ios; |
| 47 |
asio::steady_timer _timer; |
| 48 |
std::thread _thread; |
| 49 |
}; |