summaryrefslogtreecommitdiff
path: root/src/timer_wrap.h
blob: dbc23b442bea39d4556a21bb7f365dd68239095d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#ifndef SRC_TIMER_WRAP_H_
#define SRC_TIMER_WRAP_H_

#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS

#include "memory_tracker.h"
#include "env.h"
#include "uv.h"

#include <functional>

namespace node {

// Utility class that makes working with libuv timers a bit easier.
class TimerWrap final : public MemoryRetainer {
 public:
  using TimerCb = std::function<void()>;

  TimerWrap(Environment* env, const TimerCb& fn);
  TimerWrap(const TimerWrap&) = delete;

  inline Environment* env() const { return env_; }

  // Stop calling the timer callback.
  void Stop();
  // Render the timer unusable and delete this object.
  void Close();

  // Starts / Restarts the Timer
  void Update(uint64_t interval, uint64_t repeat = 0);

  void Ref();
  void Unref();

  SET_NO_MEMORY_INFO()
  SET_MEMORY_INFO_NAME(TimerWrap)
  SET_SELF_SIZE(TimerWrap)

 private:
  static void TimerClosedCb(uv_handle_t* handle);
  static void OnTimeout(uv_timer_t* timer);
  ~TimerWrap() = default;

  Environment* env_;
  TimerCb fn_;
  uv_timer_t timer_;

  friend std::unique_ptr<TimerWrap>::deleter_type;
};

class TimerWrapHandle : public MemoryRetainer  {
 public:
  TimerWrapHandle(
      Environment* env,
      const TimerWrap::TimerCb& fn);

  TimerWrapHandle(const TimerWrapHandle&) = delete;

  ~TimerWrapHandle() { Close(); }

  void Update(uint64_t interval, uint64_t repeat = 0);

  void Ref();
  void Unref();

  void Stop();
  void Close();

  void MemoryInfo(node::MemoryTracker* tracker) const override;

  SET_MEMORY_INFO_NAME(TimerWrapHandle)
  SET_SELF_SIZE(TimerWrapHandle)

 private:
  static void CleanupHook(void* data);

  TimerWrap* timer_;
};

}  // namespace node

#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS

#endif  // SRC_TIMER_WRAP_H_