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};
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
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