PHP Conference Japan 2024

EvTimer::__construct

(PECL ev >= 0.2.0)

EvTimer::__construct构造 EvTimer 观察器对象

描述

public EvTimer::__construct(
     float $after,
     float $repeat,
     callable $callback,
     mixed $data = null,
     int $priority = 0
)

构造一个 EvTimer 观察器对象。

参数

after

将计时器配置为在 after 秒后触发。

repeat

如果 repeat 为 0.0,则一旦超时到达就会自动停止。如果为正数,则计时器将自动配置为在之后每隔 repeat 秒再次触发,直到手动停止。

callback

参见 观察器回调

data

与观察器关联的自定义数据。

priority

观察器优先级

示例

示例 #1 简单计时器

<?php
// 创建并启动计时器,2 秒后触发
$w1 = new EvTimer(2, 0, function () {
echo
"已过去 2 秒\n";
});

// 创建并启动计时器,2 秒后触发,之后每秒重复一次
// 直到我们手动停止它
$w2 = new EvTimer(2, 1, function ($w) {
echo
"每秒钟调用一次,2 秒后启动\n";
echo
"迭代 = ", Ev::iteration(), PHP_EOL;

// 5 次迭代后停止观察器
Ev::iteration() == 5 and $w->stop();
// 如果进一步调用导致超过 10 次迭代,则停止观察器
Ev::iteration() >= 10 and $w->stop();
});

// 创建停止的计时器。在我们自己启动它之前,它将处于非活动状态
$w_stopped = EvTimer::createStopped(10, 5, function($w) {
echo
"作为停止状态创建的计时器的回调\n";

// 2 次迭代后停止观察器
Ev::iteration() >= 2 and $w->stop();
});

// 循环,直到调用 Ev::stop() 或所有观察器停止
Ev::run();

// 启动并查看是否有效
$w_stopped->start();
echo
"运行单个迭代\n";
Ev::run(Ev::RUN_ONCE);

echo
"重新启动第二个观察器并尝试处理相同的事件,但不阻塞\n";
$w2->again();
Ev::run(Ev::RUN_NOWAIT);

$w = new EvTimer(10, 0, function() {});
echo
"运行阻塞循环\n";
Ev::run();
echo
"END\n";
?>

以上示例将输出类似以下内容

2 seconds elapsed
is called every second, is launched after 2 seconds
iteration = 1
is called every second, is launched after 2 seconds
iteration = 2
is called every second, is launched after 2 seconds
iteration = 3
is called every second, is launched after 2 seconds
iteration = 4
is called every second, is launched after 2 seconds
iteration = 5
Run single iteration
Callback of a timer created as stopped
Restart the second watcher and try to handle the same events, but don't block
Running a blocking loop
is called every second, is launched after 2 seconds
iteration = 8
is called every second, is launched after 2 seconds
iteration = 9
is called every second, is launched after 2 seconds
iteration = 10
END
添加备注

用户贡献的备注 1 个备注

2
Jayesh Wadhwani
11 年前
传递自定义数据的示例

<?php
// 创建并启动计时器,2 秒后触发,并带有自定义数据
$w1 = new EvTimer(2, 0, function ($w) {
echo
"自定义数据: $w->data\n";
echo
"已过去 2 秒\n";
},
'abcd');
Ev::run();
?>
运行此代码将打印
自定义数据: abcd
已过去 2 秒

注意,'data' 是事件 EvWatcher 类的公共属性。
To Top