SocketService
Documentation for Redweb 0.16.1. Install that exact version when following these examples.
Route-scoped background worker. Used by SocketRoute to run ticks or lifecycle hooks tied to a specific route.
Explain it like I’m five
A SocketService is a helper that clocks in when its route starts and clocks out when the route stops, such as presence tracking or a periodic snapshot publisher.
When should I use it?
Use it for route-scoped background behavior that needs explicit startup, shutdown, and access to the owning route.
Follow the example
This API pattern illustrates the named surface; it may require application-owned classes, credentials, or assets. Start from a complete recipe for a runnable application.
import { SocketService } from 'redweb'
class ClockService extends SocketService {
constructor() { super('clock', 1000) }
onTick() {
this.route.clients.forEach((socket) => socket.sendJson({ type: 'time', now: Date.now() }))
}
}- SocketRoute constructs and initializes the service through onInit(route).
- The optional tick interval invokes onTick; simple SocketService ticks do not await earlier asynchronous ticks.
- onShutdown releases the interval; overrides must also release their application resources and call the base cleanup.
Methods and members
constructor(name, tickRateMs = null)
Stores a service id and optional tick interval; the interval is activated in onInit if onTick exists.
onInit(route)
Called once by SocketRoute, sets this.route and, if a tick interval was supplied, schedules recurring onTick execution.
onTick()
Optional; implement to run on the configured interval.
onShutdown()
Clears the tick interval; extend for cleanup hooks.
What should I watch for?
Use onInit/onShutdown, not start/stop hooks. Use FixedStepService for non-overlapping async ticks and bounded catch-up; plain SocketService does not provide those guarantees.