2024 年日本 PHP 研討會

EvTimer::__construct

(PECL ev >= 0.2.0)

EvTimer::__construct建構一個 EvTimer 監視器物件

說明

public EvTimer::__construct(
     浮點數 $after,
     浮點數 $repeat,
     可呼叫的 (callable) $callback,
     混合型別 (mixed) $data = null,
     整數 (int) $priority = 0
)

建構一個 EvTimer 監視器物件。

參數

after

設定計時器在 after 秒後觸發。

repeat

如果 repeat 為 0.0,則在達到逾時後會自動停止。如果它是正值,則計時器將自動配置為每隔 repeat 秒再次觸發,直到手動停止。

callback

參見 監視器回呼 (Watcher callbacks)

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
新增註解

使用者貢獻的註解 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