-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimer.php
65 lines (55 loc) · 1.41 KB
/
Timer.php
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
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2016/12/21 0021
* Time: 16:32
*/
namespace PushWorker;
use Exception;
class Timer
{
public static $tasks = array();
public static function init()
{
pcntl_signal(SIGALRM, array('\\PushWorker\\Timer', 'signalHandle'), false);
}
public static function signalHandle()
{
pcntl_alarm(1);
//执行任务
if (empty(self::$tasks)) {
return;
}
foreach (self::$tasks as $run_time => $task) {
$time_now = time();
if ($time_now >= $run_time) {
$func = $task[0];
$args = $task[1];
$interval = $task[2];
call_user_func_array($func, $args);
unset(self::$tasks[$run_time]);
Timer::add($interval, $func, $args);
}
}
}
public static function add($interval, $func, $args = array())
{
if ($interval <= 0) {
echo new Exception('wrong interval');
return false;
}
if (!is_callable($func)) {
echo new Exception('not callable');
return false;
} else {
$runtime = time() + $interval;
self::$tasks[$runtime] = array($func, $args, $interval);
return true;
}
}
public static function tick()
{
pcntl_alarm(1);
}
}