# SocketService

> Documentation for Redweb 0.13.0. 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.

```js
const { SocketService } = require('redweb')

class ClockService extends SocketService {
  constructor() { super('clock', 1000) }
  onTick() {
    this.route.clients.forEach((socket) => socket.sendJson({ type: 'time', now: Date.now() }))
  }
}
```

1. The service is constructed with a stable name.
2. SocketRoute starts it once the route is ready.
3. Shutdown awaits the service so timers, subscriptions, and external connections cannot leak.

## 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?

Every resource acquired in start must have a bounded and idempotent release in stop. Avoid detached timers or promises that outlive the route.
