Crow  0.3
A C++ microframework for the web
dumb_timer_queue.h
1 #pragma once
2 
3 #include <boost/asio.hpp>
4 #include <deque>
5 #include <functional>
6 #include <chrono>
7 #include <thread>
8 
9 #include "crow/logging.h"
10 
11 namespace crow
12 {
13  namespace detail
14  {
15 
16  /// Fast timer queue for fixed tick value.
18  {
19  public:
20  static int tick;
21  using key = std::pair<dumb_timer_queue*, int>;
22 
23  void cancel(key& k)
24  {
25  auto self = k.first;
26  k.first = nullptr;
27  if (!self)
28  return;
29 
30  unsigned int index = static_cast<unsigned>(k.second - self->step_);
31  if (index < self->dq_.size())
32  self->dq_[index].second = nullptr;
33  }
34 
35  /// Add a function to the queue.
36  key add(std::function<void()> f)
37  {
38  dq_.emplace_back(std::chrono::steady_clock::now(), std::move(f));
39  int ret = step_+dq_.size()-1;
40 
41  CROW_LOG_DEBUG << "timer add inside: " << this << ' ' << ret ;
42  return {this, ret};
43  }
44 
45  /// Process the queue: take functions out in time intervals and execute them.
46  void process()
47  {
48  if (!io_service_)
49  return;
50 
51  auto now = std::chrono::steady_clock::now();
52  while(!dq_.empty())
53  {
54  auto& x = dq_.front();
55  if (now - x.first < std::chrono::seconds(tick))
56  break;
57  if (x.second)
58  {
59  CROW_LOG_DEBUG << "timer call: " << this << ' ' << step_;
60  // we know that timer handlers are very simple currenty; call here
61  x.second();
62  }
63  dq_.pop_front();
64  step_++;
65  }
66  }
67 
68  void set_io_service(boost::asio::io_service& io_service)
69  {
70  io_service_ = &io_service;
71  }
72 
73  dumb_timer_queue() noexcept
74  {
75  }
76 
77  private:
78  boost::asio::io_service* io_service_{};
79  std::deque<std::pair<decltype(std::chrono::steady_clock::now()), std::function<void()>>> dq_;
80  int step_{};
81  };
82  }
83 }
crow::detail::dumb_timer_queue::add
key add(std::function< void()> f)
Add a function to the queue.
Definition: dumb_timer_queue.h:36
crow::detail::dumb_timer_queue
Fast timer queue for fixed tick value.
Definition: dumb_timer_queue.h:17
crow::detail::dumb_timer_queue::process
void process()
Process the queue: take functions out in time intervals and execute them.
Definition: dumb_timer_queue.h:46