Swoole Ticker 根据配置自动更新延时

以前的定时任务执行是这样的, 这样一来, 即使可以更新 tick_time 值, 由于定时任务没有重置, 也是徒劳.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Demo {
private static $tick_time = 250;

public function init()
{
$this->doWork();

// 子进程执行轮训时间
\swoole_timer_tick(self::$tick_time, function () {
$this->doWork();
});
}

public function doWork()
{
if (empty(Config::getWorkConfig())) return;
list($params) = Config::getWorkConfig();

// ... do real work with $params
}
}

根据上面的思路, 如果可以先更新 tick_time 然后对 ticker 进行重置, 那么是不是可以达到动态更新任务频率的效果呢?

修改后的代码如下:

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
class Demo {
// 默认每250秒执行一次
private static $default_ticker = 250;
private static $ticker = [];
private static $tick_time = [];

public function init()
{
$this->doWork();

// 子进程执行轮训时间
$process_id = App::getWorkerId();
$tick_time = isset(self::$tick_time[$process_id]) ? self::$tick_time[$process_id] : self::$default_ticker;

echo "register ticker!!! ", $process_id, " ", self::$ticker[$process_id], " interval ", $tick_time, "ms", PHP_EOL;
self::$tick_time[$process_id] = $tick_time;
self::$ticker[$process_id] = \swoole_timer_tick($tick_time, function () {
$this->doWork();
});
}

public function updateTickTime($tick_time)
{
$process_id = App::getWorkerId();

if (self::$ticker[$process_id] && self::$tick_time[$process_id] != $tick_time) {
echo "clear ticker!!! ", $process_id, " ", self::$ticker[$process_id], PHP_EOL;

self::$tick_time[$process_id] = $tick_time;
\swoole_timer_clear(self::$ticker[$process_id]);
$this->init();
}
}

public function doWork()
{
if (empty(Config::getWorkConfig())) return;
list($params) = Config::getWorkConfig();

$this->updateTickTime($params["tick_time"]);

// ... do real work with $params
}
}

至此, 既可以通过修改参数 tick_time 实现对执行频率的设定.

Donate - Support to make this site better.
捐助 - 支持我让我做得更好.