4 #include <boost/asio.hpp>
5 #include <boost/asio/basic_waitable_timer.hpp>
7 #ifndef ASIO_STANDALONE
8 #define ASIO_STANDALONE
11 #include <asio/basic_waitable_timer.hpp>
19 #include "crow/logging.h"
24 namespace asio = boost::asio;
25 using error_code = boost::system::error_code;
27 using error_code = asio::error_code;
38 using task_type = std::function<void()>;
39 using identifier_type = size_t;
42 using clock_type = std::chrono::steady_clock;
43 using time_type = clock_type::time_point;
46 const std::chrono::milliseconds tick_length =
47 std::chrono::seconds(1)) :
48 io_service_(io_service), timer_(io_service_),
49 tick_length_ms_(tick_length)
51 timer_.expires_after(tick_length_ms_);
53 std::bind(&task_timer::tick_handler,
this,
54 std::placeholders::_1));
65 CROW_LOG_DEBUG <<
"task_timer task cancelled: " <<
this <<
' ' << id;
76 identifier_type
schedule(
const task_type& task)
90 identifier_type
schedule(
const task_type& task, uint8_t timeout)
92 tasks_.insert({++highest_id_,
93 {clock_type::now() + (timeout * tick_length_ms_),
95 CROW_LOG_DEBUG <<
"task_timer scheduled: " <<
this <<
' ' <<
108 default_timeout_ = timeout;
113 return default_timeout_;
118 return tick_length_ms_;
124 time_type current_time = clock_type::now();
125 std::vector<identifier_type> finished_tasks;
127 for (
const auto& task : tasks_)
129 if (task.second.first < current_time)
131 (task.second.second)();
132 finished_tasks.push_back(task.first);
133 CROW_LOG_DEBUG <<
"task_timer called: " <<
this <<
138 for (
const auto& task : finished_tasks)
143 if (tasks_.empty()) highest_id_ = 0;
146 void tick_handler(
const error_code& ec)
152 timer_.expires_after(tick_length_ms_);
154 std::bind(&task_timer::tick_handler,
this, std::placeholders::_1));
158 asio::io_service& io_service_;
159 asio::basic_waitable_timer<clock_type> timer_;
160 std::map<identifier_type, std::pair<time_type, task_type>> tasks_;
164 identifier_type highest_id_{0};
165 std::chrono::milliseconds tick_length_ms_;
166 uint8_t default_timeout_{5};
Definition: task_timer.h:36
void cancel(identifier_type id)
Definition: task_timer.h:62
uint8_t get_default_timeout() const
Get the default timeout. (Default: 5)
Definition: task_timer.h:112
identifier_type schedule(const task_type &task, uint8_t timeout)
Schedule the given task to be executed after the given time.
Definition: task_timer.h:90
std::chrono::milliseconds get_tick_length() const
returns the length of one tick.
Definition: task_timer.h:117
void set_default_timeout(uint8_t timeout)
Definition: task_timer.h:107
identifier_type schedule(const task_type &task)
Definition: task_timer.h:76
The main namespace of the library. In this namespace is defined the most important classes and functi...