Btk
timer.hpp
1 #if !defined(_BTKUTILS_TIMER_HPP_)
2 #define _BTKUTILS_TIMER_HPP_
3 #include <tuple>
4 #include <chrono>
5 #include "../defs.hpp"
6 namespace Btk{
7  namespace Impl{
8  template<class Callable,class ...Args>
9  struct TimerInvoker:public std::tuple<Args...>{
10  Callable callable;
11  static void Run(void *__self){
12  auto *self = static_cast<TimerInvoker*>(__self);
13  std::apply(self->callable,std::forward<std::tuple<Args...>&&>(*self));
14  }
15  static void Delete(void *self){
16  delete static_cast<TimerInvoker*>(self);
17  }
18  };
19  }
20  struct TimerBase;
21  class BTKAPI Timer{
22  public:
23  Timer();
24  Timer(const Timer &) = delete;
25  Timer(Timer &&t){
26  base = t.base;
27  t.base = nullptr;
28  };
29  ~Timer();
30  Timer& set_interval(Uint32 interval);
31  Timer& start();
32  Timer& stop();
33 
34  template<class Callable,class ...Args>
35  Timer& set_callback(Callable &&callable,Args &&...args){
36  using Invoker = Impl::TimerInvoker<Callable,Args...>;
37  void *invoker = new Invoker{
38  {std::forward<Args>(args)...},
39  std::forward<Callable>(callable)
40  };
41  set_invoker(
42  Invoker::Run,
43  Invoker::Delete,
44  invoker
45  );
46  return *this;
47  }
54  bool running() const;
60  Uint32 interval()const;
61 
62 
63  Timer& set_interval(std::chrono::milliseconds ms){
64  return set_interval(ms.count());
65  }
71  static Uint32 current();
72  private:
73  typedef void (*InvokerRunFn)(void*);
74  typedef void (*InvokerCleanupFn)(void*);
79  void set_invoker(InvokerRunFn,InvokerCleanupFn,void*);
80  TimerBase *base;
81  };
82  #if 0
83  //No impl yet
93  template<class Callable,class ...Args>
94  void TimeoutCall(Uint32 interval,Callable &&callable,Args &&...args){
95 
96  }
97  #endif
98 }
99 
100 
101 #endif // _BTKUTILS_TIMER_HPP_
The Timer Impl.
Definition: timer.cpp:41
This header include many useful containers.
Definition: async.hpp:7
Definition: timer.hpp:21
Definition: timer.hpp:9