# Async Programming in Vuer ## Overview Vuer supports asynchronous programming patterns for handling parallel routines and callbacks. The tutorial demonstrates creating a server with background tasks running concurrently. ## Key Components ### Server Setup The framework uses `Vuer()` to instantiate a server with configuration options via query parameters like `reconnect=True` and `collapseMenu=True`. ### Main Function Decorator The `@app.spawn(start=True)` decorator marks the entry point as an async function that starts the application immediately. ### Task Management Sessions provide `spawn_task()` method for launching background operations. Tasks can be cancelled with `.cancel()` when no longer needed. ## Code Pattern Example The tutorial shows a main loop that: - Spawns independent background tasks - Updates scene objects continuously using `sess.upsert` - Manages task lifecycle by cancelling long-running operations after conditions are met - Uses `await sleep()` for non-blocking delays ## Complete Example ```python from vuer import Vuer from vuer.schemas import Scene, Box import asyncio import numpy as np app = Vuer( queries=dict( reconnect=True, collapseMenu=True, ), ) async def background_task(session): """A background task that runs independently""" count = 0 while True: print(f"Background task running: {count}") count += 1 await asyncio.sleep(1.0) @app.spawn(start=True) async def main(session): # Spawn a background task task = session.spawn_task(background_task(session)) # Main animation loop for i in range(100): theta = i * 0.1 x = 0.5 * np.cos(theta) z = 0.5 * np.sin(theta) # Update the box position session.upsert @ Box( args=[0.1, 0.1, 0.1], position=[x, 0.05, z], color="red", materialType="standard", key="animated-box", ) await asyncio.sleep(0.05) # Cancel the background task when done task.cancel() app.run() ``` ## Practical Features The demonstration animates a red box moving in a circular path while background tasks execute independently, illustrating how multiple asynchronous operations coexist within a single VuerSession without blocking the main rendering loop. ## Best Practices 1. **Use `session.spawn_task()`** for background operations 2. **Always use `await asyncio.sleep()`** for delays to avoid blocking 3. **Cancel tasks** when they're no longer needed to free resources 4. **Use `session.upsert`** for updating scene components ## Source Documentation: https://docs.vuer.ai/en/latest/tutorials/basics/async_programming.html