传递自定义数据的示例
<?php
// 创建并启动计时器,在 2 秒后触发,并带有自定义数据
$w1 = new EvTimer(2, 0, function ($w) {
echo "自定义数据: $w->data\n";
echo "2 秒过去了\n";
}, 'abcd');
Ev::run();
?>
运行这将输出
自定义数据: abcd
2 秒过去了
请注意,“data”是事件 EvWatcher 类的公共属性。
(PECL ev >= 0.2.0)
EvTimer::__construct — 构造 EvTimer 观察器对象
$after
,$repeat
,$callback
,$data
= null
,$priority
= 0构造 EvTimer 观察器对象。
示例 #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
传递自定义数据的示例
<?php
// 创建并启动计时器,在 2 秒后触发,并带有自定义数据
$w1 = new EvTimer(2, 0, function ($w) {
echo "自定义数据: $w->data\n";
echo "2 秒过去了\n";
}, 'abcd');
Ev::run();
?>
运行这将输出
自定义数据: abcd
2 秒过去了
请注意,“data”是事件 EvWatcher 类的公共属性。