-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathtimer.c
More file actions
60 lines (52 loc) · 1.25 KB
/
timer.c
File metadata and controls
60 lines (52 loc) · 1.25 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
#include <stdlib.h>
#include <assert.h>
#include "timer.h"
void timer_free(timer *t)
{
assert(!evtimer_pending(&t->event, NULL));
Block_release(t->cb);
free(t);
}
void evtimer_callback(evutil_socket_t fd, short events, void *arg)
{
timer *t = (timer*)arg;
t->cb();
if (!(event_get_events(&t->event) & EV_PERSIST)) {
timer_free(t);
}
}
void timer_cancel(timer *t)
{
if (!t) {
return;
}
evtimer_del(&t->event);
timer_free(t);
}
timer* timer_new(network *n, uint64_t timeout_ms, short events, timer_callback cb)
{
timer *t = alloc(timer);
t->cb = Block_copy(cb);
if (event_assign(&t->event, n->evbase, -1, events, evtimer_callback, t)) {
timer_free(t);
return NULL;
}
if (timeout_ms) {
timeval timeout = {
.tv_sec = timeout_ms / 1000,
.tv_usec = (timeout_ms % 1000) * 1000
};
evtimer_add(&t->event, &timeout);
} else {
event_active(&t->event, 0, 0);
}
return t;
}
timer* timer_start(network *n, uint64_t timeout_ms, timer_callback cb)
{
return timer_new(n, timeout_ms, 0, cb);
}
timer* timer_repeating(network *n, uint64_t timeout_ms, timer_callback cb)
{
return timer_new(n, timeout_ms, EV_PERSIST, cb);
}