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_context_(io_context), timer_(io_context_),
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_context& io_context_;
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};
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