Core\Sse::setRetryDelay
$sse->setRetryDelay(Core\Time\Duration $after): void$sse->setRetryDelay( Core\Time\Duration $after, ): void
Tells the client how long to wait before it reconnects to the event stream.
A browser's EventSource reconnects on its own when a stream ends, after a short wait the browser chooses. setRetryDelay() sends a new wait time to the client, as a retry: line. This line is not an event, so the client's event handlers do not run for it. The time is a Core\Time\Duration, and it is sent in milliseconds. A wait shorter than one millisecond is sent as 0.
A negative wait is not allowed, and setRetryDelay() throws a LogicError. Nothing is sent in that case.
The examples below set a wait of five seconds, show the error for a negative wait, and ask clients to come back later before a server restart.
Parameters
$afterCore\Time\DurationHow long the client waits before it reconnects. It is sent in whole milliseconds. A wait shorter than one millisecond is sent as0, without an error.
Return value
Returns void. Nothing. The retry: line is added to the response body.
Errors
LogicError$afteris negative. A wait cannot be shorter than zero.
Changelog
| Version | Change |
|---|---|
0.0.6 | Core\Sse::startStream starts an event stream, and setRetryDelay sets how long a browser waits before it connects again. The old names were stream and retry. |
Examples
Waiting five seconds
<?nvs// Shows how to tell the browser to wait five seconds before it reconnects.
Core\Sse $sse = Core\Sse::startStream();// This prints `retry: 5000`. The wait is always sent in milliseconds.$sse->setRetryDelay(Core\Time\Duration::seconds(5));$sse->send('hello');retry: 5000
data: helloA negative wait
<?nvs// Shows what `setRetryDelay()` does with a wait that is less than zero.
Core\Sse $sse = Core\Sse::startStream();// A negative wait throws a `LogicError`, and nothing is sent.// This prints `the wait cannot be negative`.try { $sse->setRetryDelay(Core\Time\Duration::seconds(-1));} catch (LogicError $e) { echo "the wait cannot be negative\n";}the wait cannot be negativeBefore a planned restart
<?nvs// Shows a live price feed that asks its clients to come back later, before the server restarts.
Core\Sse $sse = Core\Sse::startStream();$sse->send(['symbol' => 'ACME', 'price' => 1842], event: 'price');
// The server restarts soon. Clients should wait ten minutes, so they do not all reconnect at once.// This prints `retry: 600000`, then the `closing` event.$sse->setRetryDelay(Core\Time\Duration::minutes(10));$sse->send('back in ten minutes', event: 'closing');event: pricedata: {"symbol":"ACME","price":1842}
retry: 600000
event: closingdata: back in ten minutes