1 /*
2 +----------------------------------------------------------------------+
3 | Swoole |
4 +----------------------------------------------------------------------+
5 | This source file is subject to version 2.0 of the Apache license, |
6 | that is bundled with this package in the file LICENSE, and is |
7 | available through the world-wide-web at the following url: |
8 | http://www.apache.org/licenses/LICENSE-2.0.html |
9 | If you did not receive a copy of the Apache2.0 license and are unable|
10 | to obtain it through the world-wide-web, please send a note to |
11 | license@swoole.com so we can mail you a copy immediately. |
12 +----------------------------------------------------------------------+
13 | @link https://www.swoole.com/ |
14 | @contact team@swoole.com |
15 | @license https://github.com/swoole/swoole-src/blob/master/LICENSE |
16 | @author Tianfeng Han <mikan.tenny@gmail.com> |
17 +----------------------------------------------------------------------+
18 */
19
20 #include "test_core.h"
21 #include "swoole_util.h"
22
23 using swoole::Timer;
24 using swoole::TimerNode;
25
TEST(timer,sys)26 TEST(timer, sys) {
27 SwooleG.use_signalfd = 0;
28 int timer1_count = 0;
29 int timer2_count = 0;
30 int timer_running = true;
31
32 uint64_t ms1 = swoole::time<std::chrono::milliseconds>();
33
34 swoole_timer_add(
35 20, false, [&](Timer *, TimerNode *) { timer1_count++; }, nullptr);
36
37 swoole_timer_add(
38 100,
39 true,
40 [&](Timer *, TimerNode *tnode) {
41 timer2_count++;
42 if (timer2_count == 5) {
43 swoole_timer_del(tnode);
44 timer_running = false;
45 }
46 },
47 nullptr);
48
49 while (1) {
50 sleep(10);
51 if (SwooleG.signal_alarm) {
52 swoole_timer_select();
53 if (!timer_running) {
54 break;
55 }
56 }
57 }
58
59 uint64_t ms2 = swoole::time<std::chrono::milliseconds>();
60
61 swoole_timer_free();
62
63 ASSERT_LE(ms2 - ms1, 510);
64 ASSERT_EQ(timer1_count, 1);
65 ASSERT_EQ(timer2_count, 5);
66 }
67
TEST(timer,async)68 TEST(timer, async) {
69 int timer1_count = 0;
70 int timer2_count = 0;
71
72 swoole_event_init(SW_EVENTLOOP_WAIT_EXIT);
73
74 uint64_t ms1 = swoole::time<std::chrono::milliseconds>();
75 swoole_timer_after(
76 20, [&](Timer *, TimerNode *) { timer1_count++; }, nullptr);
77
78 swoole_timer_tick(
79 100,
80 [&](Timer *, TimerNode *tnode) {
81 timer2_count++;
82 if (timer2_count == 5) {
83 swoole_timer_del(tnode);
84 }
85 },
86 nullptr);
87
88 swoole_event_wait();
89 uint64_t ms2 = swoole::time<std::chrono::milliseconds>();
90 ASSERT_LE(ms2 - ms1, 510);
91 ASSERT_EQ(timer1_count, 1);
92 ASSERT_EQ(timer2_count, 5);
93 }
94