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
"结束\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 笔记

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