-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.cpp
111 lines (98 loc) · 1.98 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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <iostream>
#include<sys/time.h>
#include<string>
#include"timer.h"
#include"epoll.h"
using namespace std;
TimerNode::TimerNode(SP_request _request, int timeout):deleted(false),request(_request)
{
struct timeval now;
gettimeofday(&now,NULL);
//以毫秒记
expired_time = ((now.tv_sec*1000)+(now.tv_usec/1000)) + timeout;
}
TimerNode::~TimerNode()
{
/*临时变量request*/
if(request)
{
Epoll::epoll_del(request->getFd());
}
}
void TimerNode::update( int timeout )
{
struct timeval now;
gettimeofday(&now,NULL);
expired_time = ((now.tv_sec*1000)+(now.tv_usec/1000)) + timeout;
}
/*判断定时器是否超时*/
bool TimerNode::isvalid()
{
struct timeval now;
gettimeofday(&now,NULL);
size_t curr = ((now.tv_sec*1000)+(now.tv_usec/1000));
if(curr<expired_time)
{
return true;
}
else
{
this->setDeleted();
return false;
}
}
/*清理请求*/
void TimerNode::clearReq()
{
request->close_conn(true);
this->setDeleted();
}
inline void TimerNode::setDeleted()
{
deleted = true;
}
inline bool TimerNode::isDeleted() const
{
return deleted;
}
inline size_t TimerNode::getExpiredTime()const
{
return expired_time;
}
TimerManager::TimerManager()
{
}
TimerManager::~TimerManager()
{
}
void TimerManager::addTimer(SP_request _request, int timeout)
{
SP_TimerNode new_node(new TimerNode(_request,timeout));
{
MutexLockGuard locker(lock);
TimerHeap.push(new_node);
}
_request->linkTimer(new_node);//TODO
}
void TimerManager::addTimer(SP_TimerNode timer_node)
{
}
void TimerManager::hanlde_expired_event()
{
MutexLockGuard locker(lock);
while(!TimerHeap.empty())
{
SP_TimerNode curr_node = TimerHeap.top();
if(curr_node->isDeleted())
{
TimerHeap.pop();
}
else if(curr_node->isvalid()==false)
{
TimerHeap.pop();
}
else{
break;
}
}
}