Skip to content

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 as 0, without an error.

Return value

Returns void. Nothing. The retry: line is added to the response body.

Errors

  • LogicError$after is negative. A wait cannot be shorter than zero.

Changelog

VersionChange
0.0.6Core\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');
Output
retry: 5000
data: hello

A 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";
}
Output
the wait cannot be negative

Before 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');
Output
event: price
data: {"symbol":"ACME","price":1842}
retry: 600000
event: closing
data: back in ten minutes