File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ <?php
2+ /**
3+ * 异步协程sleep
4+ * 类似sleep,但是异步非阻塞
5+ * @author camera360_server@camera360.com
6+ * @copyright Chengdu pinguo Technology Co.,Ltd.
7+ */
8+
9+ namespace PG \MSF \Coroutine ;
10+
11+ class Sleep extends Base
12+ {
13+ /**
14+ * sleep的时间
15+ * @var int
16+ */
17+ public $ __sleepTime ;
18+
19+ /**
20+ * @param int $mSec 时间,单位为毫秒
21+ * @return $this
22+ */
23+ public function goSleep (int $ mSec )
24+ {
25+ $ this ->__sleepTime = $ mSec ;
26+ $ this ->requestId = $ this ->getContext ()->getLogId ();
27+ $ this ->setTimeout ($ mSec + 1000 ); //协程超时时间要比睡眠时间更长
28+
29+ getInstance ()->scheduler ->IOCallBack [$ this ->requestId ][] = $ this ;
30+ $ keys = array_keys (getInstance ()->scheduler ->IOCallBack [$ this ->requestId ]);
31+ $ this ->ioBackKey = array_pop ($ keys );
32+
33+ $ this ->send (function () {
34+ if (empty (getInstance ()->scheduler ->taskMap [$ this ->requestId ])) {
35+ return ;
36+ }
37+
38+ $ this ->result = true ;
39+ $ this ->ioBack = true ;
40+ $ this ->nextRun ();
41+ });
42+ return $ this ;
43+ }
44+
45+ /**
46+ * 通过定时器来模拟异步IO
47+ * @param callable $callback 定时器回调函数
48+ * @return $this
49+ */
50+ public function send ($ callback )
51+ {
52+ swoole_timer_after ($ this ->__sleepTime , $ callback );
53+ return $ this ;
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments