-
Notifications
You must be signed in to change notification settings - Fork 41
/
PriorityQueueTimer.h
53 lines (38 loc) · 1.03 KB
/
PriorityQueueTimer.h
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
// Copyright © 2021 [email protected] All rights reserved.
// See accompanying files LICENSE
#pragma once
#include "TimerBase.h"
#include <vector>
#include <unordered_map>
// timer scheduler implemented by priority queue(min-heap)
//
// complexity:
// StartTimer CancelTimer PerTick
// O(log N) O(log N) O(1)
//
struct TimerNode;
class PriorityQueueTimer : public TimerBase
{
public:
public:
PriorityQueueTimer();
~PriorityQueueTimer();
TimerSchedType Type() const override
{
return TimerSchedType::TIMER_PRIORITY_QUEUE;
}
// start a timer after `duration` milliseconds
int Start(uint32_t duration, TimeoutAction action) override;
// cancel a timer
bool Cancel(int timer_id) override;
int Update(int64_t now = 0) override;
int Size() const override
{
return (int)timers_.size();
}
private:
void clear();
private:
std::vector<TimerNode*> timers_; // binary timer heap
std::unordered_map<int, TimerNode*> ref_; // to make O(1) lookup
};