-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathtimer.cc
67 lines (57 loc) · 2.28 KB
/
timer.cc
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
/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "swoole_timer.h"
#include "swoole_signal.h"
#include <signal.h>
namespace swoole {
static int SystemTimer_set(Timer *timer, long next_msec);
bool Timer::init_with_system_timer() {
set = SystemTimer_set;
close = [](Timer *timer) { SystemTimer_set(timer, -1); };
swoole_signal_set(SIGALRM, [](int sig) { SwooleG.signal_alarm = true; });
return true;
}
/**
* setitimer
*/
static int SystemTimer_set(Timer *timer, long next_msec) {
struct itimerval timer_set;
struct timeval now;
if (gettimeofday(&now, nullptr) < 0) {
swoole_sys_warning("gettimeofday() failed");
return SW_ERR;
}
if (next_msec > 0) {
int sec = next_msec / 1000;
int msec = next_msec % 1000;
timer_set.it_interval.tv_sec = sec;
timer_set.it_interval.tv_usec = msec * 1000;
timer_set.it_value.tv_sec = sec;
timer_set.it_value.tv_usec = timer_set.it_interval.tv_usec;
if (timer_set.it_value.tv_usec > 1e6) {
timer_set.it_value.tv_usec = timer_set.it_value.tv_usec - 1e6;
timer_set.it_value.tv_sec += 1;
}
} else {
timer_set = {};
}
if (setitimer(ITIMER_REAL, &timer_set, nullptr) < 0) {
swoole_sys_warning("setitimer() failed");
return SW_ERR;
}
return SW_OK;
}
} // namespace swoole