You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
An Agent can schedule tasks to be run in the future by calling `this.schedule(when, callback, data)`, where `when` can be a delay, a `Date`, or a cron string; `callback` the function name to call, and `data` is an object of data to pass to the function.
11
11
12
-
Scheduled tasks can do anything a request or message from a user can: make requests, query databases, send emails, read+write state, etc.
12
+
Scheduled tasks can do anything a request or message from a user can: make requests, query databases, send emails, read+write state: scheduled tasks can invoke any regular method on your Agent.
13
13
14
14
### Scheduling tasks
15
15
16
-
You can call `this.schedule` within any method on an Agent, and schedule tens-of-thousands of tasks per individual Agent.
16
+
You can call `this.schedule` within any method on an Agent, and schedule tens-of-thousands of tasks per individual Agent:
Users and clients can connect to an Agent directly over WebSockets, allowing long-running, bi-directional communication with your Agent as it operates.
12
+
13
+
To enable an Agent to accept WebSockets, define `onConnect` and `onMessage` methods on your Agent.
14
+
15
+
*`onConnect(connection: Connection, ctx: ConnectionContext)` is called when a client establishes a new WebSocket connection. The original HTTP request, including request headers, cookies and the URL itself, are available on `ctx.request`.
16
+
*`onMessage(connection: Connection, message: WSMessage)` is called for each incoming WebSocket message. Messages are one of `ArrayBuffer | ArrayBufferView | string`, and you can send messages back to a client using `connection.send()`. You can distinguish between client connections by checking `connection.id`, which is unique for each connected client.
17
+
18
+
Here's an example of an Agent that echoes back any message it receives:
The Agent framework includes a useful helper package for connecting directly to your agent (or other agents) from a client application. Import `@cloudflare/agents/client`, create an instance of `AgentClient` and use it to connect to an instance of your Agent:
The `useAgent` hook automatically handles the lifecycle of the connection, ensuring that it is properly initialized and cleaned up when the component mounts and unmounts. You can also [combine `useAgent` with `useState`](/agents/examples/manage-and-sync-state/) to automatically synchronize state across all clients connected to your agent.
124
+
125
+
## Handling WebSocket events
126
+
127
+
Define `onError` and `onClose` methods on your Agent to explicitly handle WebSocket client errors and close events. Log errors, clean up state, and/or emit metrics:
0 commit comments