傳遞自訂資料的範例
<?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 監視器物件。
after
設定計時器在 after
秒後觸發。
repeat
如果 repeat 為 0.0
,則在達到逾時後會自動停止。如果它是正值,則計時器將自動配置為每隔 repeat 秒再次觸發,直到手動停止。
callback
data
與監視器關聯的自訂資料。
priority
範例 #1 簡單計時器
<?php
// Create and start timer firing after 2 seconds
$w1 = new EvTimer(2, 0, function () {
echo "2 seconds elapsed\n";
});
// Create and launch timer firing after 2 seconds repeating each second
// until we manually stop it
$w2 = new EvTimer(2, 1, function ($w) {
echo "is called every second, is launched after 2 seconds\n";
echo "iteration = ", Ev::iteration(), PHP_EOL;
// Stop the watcher after 5 iterations
Ev::iteration() == 5 and $w->stop();
// Stop the watcher if further calls cause more than 10 iterations
Ev::iteration() >= 10 and $w->stop();
});
// Create stopped timer. It will be inactive until we start it ourselves
$w_stopped = EvTimer::createStopped(10, 5, function($w) {
echo "Callback of a timer created as stopped\n";
// Stop the watcher after 2 iterations
Ev::iteration() >= 2 and $w->stop();
});
// Loop until Ev::stop() is called or all of watchers stop
Ev::run();
// Start and look if it works
$w_stopped->start();
echo "Run single iteration\n";
Ev::run(Ev::RUN_ONCE);
echo "Restart the second watcher and try to handle the same events, but don't block\n";
$w2->again();
Ev::run(Ev::RUN_NOWAIT);
$w = new EvTimer(10, 0, function() {});
echo "Running a blocking loop\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
傳遞自訂資料的範例
<?php
// 建立並啟動計時器,在 2 秒後觸發,並帶有自訂資料
$w1 = new EvTimer(2, 0, function ($w) {
echo "自訂資料: $w->data\n";
echo "2 秒已過\n";
}, 'abcd');
Ev::run();
?>
執行此程式碼將會印出
自訂資料: abcd
2 秒已過
請注意,'data' 是事件 EvWatcher 類別的公開屬性。