-
-
Notifications
You must be signed in to change notification settings - Fork 354
/
Copy pathtimer.cpp
53 lines (40 loc) · 1.39 KB
/
timer.cpp
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
#include <mbgl/util/timer.hpp>
#include <CoreFoundation/CoreFoundation.h>
namespace mbgl {
namespace util {
CFTimeInterval toCFTimeInterval(Duration duration) {
return std::chrono::duration<CFTimeInterval>(duration).count();
}
CFAbsoluteTime toCFAbsoluteTime(Duration duration) {
return CFAbsoluteTimeGetCurrent() + toCFTimeInterval(duration);
}
class Timer::Impl {
public:
Impl(Duration timeout, Duration repeat, std::function<void()>&& fn)
: task(std::move(fn)),
loop(CFRunLoopGetCurrent()) {
CFRunLoopTimerContext context = {0, this, nullptr, nullptr, nullptr};
timer = CFRunLoopTimerCreate(
kCFAllocatorDefault, toCFAbsoluteTime(timeout), toCFTimeInterval(repeat), 0, 0, perform, &context);
CFRunLoopAddTimer(loop, timer, kCFRunLoopDefaultMode);
}
~Impl() {
CFRunLoopRemoveTimer(loop, timer, kCFRunLoopDefaultMode);
CFRelease(timer);
}
private:
static void perform(CFRunLoopTimerRef, void* info) { reinterpret_cast<Impl*>(info)->task(); }
std::function<void()> task;
CFRunLoopRef loop;
CFRunLoopTimerRef timer;
};
Timer::Timer() = default;
Timer::~Timer() = default;
void Timer::start(Duration timeout, Duration repeat, std::function<void()>&& cb) {
impl = std::make_unique<Impl>(timeout, repeat, std::move(cb));
}
void Timer::stop() {
impl.reset();
}
} // namespace util
} // namespace mbgl