1 #include "env-inl.h"
2 #include "memory_tracker-inl.h"
3 #include "timer_wrap.h"
4 #include "uv.h"
5
6 namespace node {
7
TimerWrap(Environment * env,const TimerCb & fn)8 TimerWrap::TimerWrap(Environment* env, const TimerCb& fn)
9 : env_(env),
10 fn_(fn) {
11 uv_timer_init(env->event_loop(), &timer_);
12 timer_.data = this;
13 }
14
Stop()15 void TimerWrap::Stop() {
16 if (timer_.data == nullptr) return;
17 uv_timer_stop(&timer_);
18 }
19
Close()20 void TimerWrap::Close() {
21 timer_.data = nullptr;
22 env_->CloseHandle(reinterpret_cast<uv_handle_t*>(&timer_), TimerClosedCb);
23 }
24
TimerClosedCb(uv_handle_t * handle)25 void TimerWrap::TimerClosedCb(uv_handle_t* handle) {
26 std::unique_ptr<TimerWrap> ptr(
27 ContainerOf(&TimerWrap::timer_,
28 reinterpret_cast<uv_timer_t*>(handle)));
29 }
30
Update(uint64_t interval,uint64_t repeat)31 void TimerWrap::Update(uint64_t interval, uint64_t repeat) {
32 if (timer_.data == nullptr) return;
33 uv_timer_start(&timer_, OnTimeout, interval, repeat);
34 }
35
Ref()36 void TimerWrap::Ref() {
37 if (timer_.data == nullptr) return;
38 uv_ref(reinterpret_cast<uv_handle_t*>(&timer_));
39 }
40
Unref()41 void TimerWrap::Unref() {
42 if (timer_.data == nullptr) return;
43 uv_unref(reinterpret_cast<uv_handle_t*>(&timer_));
44 }
45
OnTimeout(uv_timer_t * timer)46 void TimerWrap::OnTimeout(uv_timer_t* timer) {
47 TimerWrap* t = ContainerOf(&TimerWrap::timer_, timer);
48 t->fn_();
49 }
50
TimerWrapHandle(Environment * env,const TimerWrap::TimerCb & fn)51 TimerWrapHandle::TimerWrapHandle(
52 Environment* env,
53 const TimerWrap::TimerCb& fn) {
54 timer_ = new TimerWrap(env, fn);
55 env->AddCleanupHook(CleanupHook, this);
56 }
57
Stop()58 void TimerWrapHandle::Stop() {
59 if (timer_ != nullptr)
60 return timer_->Stop();
61 }
62
Close()63 void TimerWrapHandle::Close() {
64 if (timer_ != nullptr) {
65 timer_->env()->RemoveCleanupHook(CleanupHook, this);
66 timer_->Close();
67 }
68 timer_ = nullptr;
69 }
70
Ref()71 void TimerWrapHandle::Ref() {
72 if (timer_ != nullptr)
73 timer_->Ref();
74 }
75
Unref()76 void TimerWrapHandle::Unref() {
77 if (timer_ != nullptr)
78 timer_->Unref();
79 }
80
Update(uint64_t interval,uint64_t repeat)81 void TimerWrapHandle::Update(uint64_t interval, uint64_t repeat) {
82 if (timer_ != nullptr)
83 timer_->Update(interval, repeat);
84 }
85
MemoryInfo(MemoryTracker * tracker) const86 void TimerWrapHandle::MemoryInfo(MemoryTracker* tracker) const {
87 if (timer_ != nullptr)
88 tracker->TrackField("timer", *timer_);
89 }
90
CleanupHook(void * data)91 void TimerWrapHandle::CleanupHook(void* data) {
92 static_cast<TimerWrapHandle*>(data)->Close();
93 }
94
95 } // namespace node
96