-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTimer.cpp
More file actions
64 lines (52 loc) · 1.68 KB
/
Timer.cpp
File metadata and controls
64 lines (52 loc) · 1.68 KB
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
#include "Timer.h"
#include <sys/time.h>
TimerNode::TimerNode(std::shared_ptr<HttpData> requestData, const long &timeout): deleted_(false), SPHttpData(requestData) {
gettimeofday(&now_tmp, NULL);
// time unit is microseconds,
// if use tv_sec, unit is secondes.
expiredTime_ = now_tmp.tv_usec + timeout;
}
TimerNode::~TimerNode() {
if (SPHttpData) SPHttpData->handleClose();
}
TimerNode::TimerNode(const TimerNode &tn)
: SPHttpData(tn.SPHttpData), expiredTime_(0) {}
bool TimerNode::isValid() {
gettimeofday(&now_tmp, NULL);
if (now_tmp.tv_usec < expiredTime_) return true;
else {
this->setDeleted();
return false;
}
}
void TimerNode::clearReq() {
SPHttpData.reset();
this->setDeleted();
}
TimerManager::TimerManager() {}
TimerManager::~TimerManager() {}
void TimerManager::addTimer(std::shared_ptr<HttpData> SPHttpData, const long &timeout) {
SPTimerNode new_node(new TimerNode(SPHttpData, timeout));
timerNodeQueue.push(new_node);
SPHttpData->linkTimer(new_node);
}
/* the time manager logic:
*
* because of:(1) priority queue do not support randomaccess
* (2) even if PQ do, randomly delete a node will destroy the structure of PQ.
*
* so: the timenode which is set delete_=true will be deleted
* (1) until it timeout
* (2) or all node(befor it) was deleted
*
* advantage: (1) don't have to travese the PQ or rebuilt the PQ.
* (2) after timeout, the http-request occurs again,
*/
void TimerManager::handleExpiredEvent() {
while (!timerNodeQueue.empty()) {
SPTimerNode ptimer_now = timerNodeQueue.top();
if (ptimer_now->isDeleted()) timerNodeQueue.pop();
else if (ptimer_now->isValid() == false) timerNodeQueue.pop();
else break;
}
}