-
Notifications
You must be signed in to change notification settings - Fork 0
/
stp_timer.c
70 lines (56 loc) · 1.27 KB
/
stp_timer.c
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
#include "stp_timer.h"
#include "log.h"
bool timer_list_initialized = false;
struct list_head timer_list;
// one tick is 1/256 second
long long int time_tick_now()
{
struct timeval now;
gettimeofday(&now, NULL);
return (long long int)(now.tv_sec) * 256 + now.tv_usec * 256 / 1000000;
}
void stp_init_timer(stp_timer_t *timer, \
int timeout, timeout_handler func, void *arg)
{
if (!timer_list_initialized) {
init_list_head(&timer_list);
timer_list_initialized = true;
}
init_list_head(&timer->list);
timer->active = false;
timer->timeout = timeout;
timer->func = func;
timer->arg = arg;
list_add_tail(&timer->list, &timer_list);
}
void stp_start_timer(stp_timer_t *timer, long long int time)
{
timer->active = true;
timer->time = time;
}
void stp_stop_timer(stp_timer_t *timer)
{
timer->active = false;
}
bool stp_check_timer(stp_timer_t *timer, long long int now)
{
if (timer->active) {
if (now >= timer->time + timer->timeout) {
timer->active = false;
return true;
}
}
return false;
}
void stp_timer_run_once(long long int now)
{
if (!timer_list_initialized) {
log(ERROR, "no timer in the list.");
return ;
}
stp_timer_t *timer;
list_for_each_entry(timer, &timer_list, list) {
if (stp_check_timer(timer, now))
timer->func(timer->arg);
}
}