Scope::disposeAfterTimeout
(PHP 8.6+, True Async 1.0)
public function disposeAfterTimeout(int $timeout): void
Schedules the scope to be closed after a specified timeout. When the timeout expires, dispose() is called, cancelling all coroutines and closing the scope. This is convenient for setting a maximum scope lifetime.
Parameters
timeout — time in milliseconds before the scope is automatically closed.
Return Value
No value is returned.
Examples
Example #1 Limiting execution time
<?php
use Async\Scope;
$scope = new Scope();
// Scope will be closed after 10 seconds
$scope->disposeAfterTimeout(10_000);
$scope->spawn(function() {
try {
// Long operation
\Async\delay(60_000);
} catch (\Async\CancelledException) {
echo "Task cancelled by scope timeout\n";
}
});
$scope->awaitCompletion();
Example #2 Scope with a limited lifetime
<?php
use Async\Scope;
$scope = new Scope();
$scope->disposeAfterTimeout(5000); // 5 seconds for all work
$scope->spawn(function() {
\Async\delay(1000);
echo "Task 1: OK\n";
});
$scope->spawn(function() {
\Async\delay(2000);
echo "Task 2: OK\n";
});
$scope->spawn(function() {
\Async\delay(30_000); // Won't finish in time
echo "Task 3: OK\n"; // Will not be printed
});
$scope->awaitCompletion();
See Also
- Scope::dispose — Immediate scope closure
- Scope::disposeSafely — Safe scope closure
- timeout() — Global timeout function