Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add event handling sample #231

Merged
merged 5 commits into from
Nov 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions docs/ten_framework/ten_packages/python_async_extension.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,45 @@ class DefaultAsyncExtension(AsyncExtension):

Each method simulates a delay using `await asyncio.sleep()`.

## FAQ

### Aysnc loop for event handling

- Create a queue: use `asyncio.Queue`.
- Create an async task for event handling.

Here is the sample code:

```python
import asyncio
from ten import AsyncExtension, AsyncTenEnv

class DefaultAsyncExtension(AsyncExtension):
queue = asyncio.Queue()
loop:asyncio.AbstractEventLoop = None

async def on_start(self, ten_env: AsyncTenEnv) -> None:
self.loop = asyncio.get_event_loop()

self.loop.create_task(self._consume())

async def on_stop(self, ten_env: AsyncTenEnv) -> None:
self.queue.put(None)

async def _consume(self) -> None:
while True
try:
value = await self.queue.get()
if value is None:
self.ten_env.log_info("async loop exit")
break

# Code for processing values retrieved from the queue.

except Exception as e:
self.ten_env.log_error(f"Failed to handle {e}")
```

## Conclusion

TEN's Python async extension provide a powerful way to handle long-running tasks asynchronously. By integrating Python’s `asyncio` framework, the extensions ensure that operations such as network calls or file handling are efficient and non-blocking. This makes TEN a great choice for building scalable, modular applications with asynchronous capabilities.
Loading