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;
36 using task_type = std::function<void()>;
37 using identifier_type = size_t;
40 using clock_type = std::chrono::steady_clock;
41 using time_type = clock_type::time_point;
45 io_service_(io_service), timer_(io_service_)
47 timer_.expires_after(std::chrono::seconds(1));
49 std::bind(&task_timer::tick_handler,
this, std::placeholders::_1));
54 void cancel(identifier_type
id)
57 CROW_LOG_DEBUG <<
"task_timer cancelled: " <<
this <<
' ' << id;
67 identifier_type
schedule(
const task_type& task)
73 CROW_LOG_DEBUG <<
"task_timer scheduled: " <<
this <<
' ' << highest_id_;
86 identifier_type
schedule(
const task_type& task, std::uint8_t timeout)
88 tasks_.insert({++highest_id_,
89 {clock_type::now() + std::chrono::seconds(timeout), task}});
90 CROW_LOG_DEBUG <<
"task_timer scheduled: " <<
this <<
' ' << highest_id_;
106 time_type current_time = clock_type::now();
107 std::vector<identifier_type> finished_tasks;
109 for (
const auto& task : tasks_)
111 if (task.second.first < current_time)
113 (task.second.second)();
114 finished_tasks.push_back(task.first);
115 CROW_LOG_DEBUG <<
"task_timer called: " <<
this <<
' ' << task.first;
119 for (
const auto& task : finished_tasks)
123 if (tasks_.empty()) highest_id_ = 0;
126 void tick_handler(
const error_code& ec)
132 timer_.expires_after(std::chrono::seconds(1));
134 std::bind(&task_timer::tick_handler,
this, std::placeholders::_1));
138 std::uint8_t default_timeout_{5};
139 asio::io_service& io_service_;
140 asio::basic_waitable_timer<clock_type> timer_;
141 std::map<identifier_type, std::pair<time_type, task_type>> tasks_;
145 identifier_type highest_id_{0};
A class for scheduling functions to be called after a specific amount of ticks. A tick is equal to 1 ...
Definition: task_timer.h:34
identifier_type schedule(const task_type &task, std::uint8_t timeout)
Schedule the given task to be executed after the given time.
Definition: task_timer.h:86
void set_default_timeout(std::uint8_t timeout)
Set the default timeout for this task_timer instance. (Default: 5)
Definition: task_timer.h:98
identifier_type schedule(const task_type &task)
Schedule the given task to be executed after the default amount of ticks.
Definition: task_timer.h:67
std::uint8_t get_default_timeout() const
Get the default timeout. (Default: 5)
Definition: task_timer.h:101
The main namespace of the library. In this namespace is defined the most important classes and functi...