How to shutdown the room and gracefully exit the l...
# ask-ai
a
How to shutdown the room and gracefully exit the livekit session after a certain period of time
✅ 1
t
Thanks for reaching out, Shashin. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’ll walk you through how to shut down a room and gracefully exit a LiveKit session after a set period. Summary of the approach • Start a timer when the session/room starts. • When the timer expires, send a user-facing message (optional), call the graceful shutdown method, and optionally delete the room. • Use shutdown hooks for cleanup tasks (save state, logs) if needed. Python (async) example 1. Start a background timer task when session begins. 2. On expiry: announce, call
session.shutdown(drain=True)
(graceful) or
await session.aclose()
(immediate), then optionally delete the room via the API. Example sketch:
Copy code
import asyncio

async def session_timer(session, ctx, duration_seconds):
    try:
        await asyncio.sleep(duration_seconds)
        await session.say("Session time is up. Closing the room now.")
        await asyncio.sleep(1.0)  # let message deliver
        session.shutdown("Session timer expired")  # graceful shutdown
        # Optionally delete the room:
        # await api_client.room.delete_room(api.DeleteRoomRequest(room=ctx.job.room.name))
    except asyncio.CancelledError:
        pass

# when session starts
timer_task = asyncio.create_task(session_timer(session, ctx, 180))  # e.g., 3 minutes

# cancel timer if user leaves early
timer_task.cancel()
Node.js / JS (conceptual) • Use a timer or background task. • Call
ctx.shutdown()
for graceful shutdown or
ctx.aclose()
to close immediately. • Use
ctx.add_shutdown_callback()
to register cleanup actions. Deleting the room automatically • In Python, set
delete_room_on_close=True
in
RoomOptions
to delete the room when the session ends. • Or call the RoomService API:
RoomServiceClient.deleteRoom()
(server-side) to kick everyone and remove the room. Cleanup hooks • Register shutdown callbacks with
ctx.add_shutdown_callback()
to persist user state or run other cleanup. The framework waits (by default) up to 10s for hooks to finish. If you’d like, tell me: • Which SDK/language you’re using (Python or Node.js), and • Whether you want the room deleted automatically or left for reconnection, and I’ll provide a ready-to-run example tailored to your codebase. Sources: Job lifecycle | LiveKit Documentation | Agent session | LiveKit Documentation | Build a salary negotiation coach with a LemonSlice avatar | LiveKit, with interactive elements
a
Auto end the session after certain time period. For instance, a call should be alive for 2 min max
t
Thanks — quick clarifying questions so I can give a precise example: 1. Which SDK/language are you using: Python or Node.js (or web/browser)? 2. Do you want the room deleted when the call ends, or just disconnect participants and keep the room? 3. Should participants be notified before the call ends (e.g., a 10s warning)? Answer these and I’ll provide a ready-to-run snippet for a 2-minute auto‑end. , with interactive elements
a
1. Python 2. End the room as well 3. Yes
t
Thanks — based on your answers (Python, delete room, send warning), here’s a concise, ready-to-run pattern you can adapt. It: • Starts a 2-minute timer when the session begins • Sends a 10s warning to participants • Gracefully shuts down the session • Deletes the room when the session closes Example (async Python sketch):
Copy code
import asyncio
from livekit import api
import os

# create API client for explicit room deletion (optional if using RoomOptions.delete_room_on_close)
api_client = api.LiveKitAPI(
    os.getenv("LIVEKIT_URL"),
    os.getenv("LIVEKIT_API_KEY"),
    os.getenv("LIVEKIT_API_SECRET"),
)

async def auto_end_session(ctx, session, room_name, duration_seconds=120, warning_seconds=10):
    try:
        # wait until warning time
        await asyncio.sleep(duration_seconds - warning_seconds)
        await session.say(f"Call will end in {warning_seconds} seconds.")
        await asyncio.sleep(warning_seconds)

        # graceful shutdown of session (allows pending ops to drain)
        session.shutdown("Session timer expired")

        # give shutdown flow a moment to run
        await asyncio.sleep(1.0)

        # Option A: delete room explicitly via API
        await api_client.room.delete_room(api.DeleteRoomRequest(room=room_name))

        # Option B (alternative): if you configured RoomOptions with delete_room_on_close=True,
        # the room will be deleted automatically when the session closes; skip explicit delete.
    except asyncio.CancelledError:
        # cancel timer if user left earlier
        return
How to wire it up 1. When the session/room starts, create the task: ◦
timer_task = asyncio.create_task(auto_end_session(ctx, session, ctx.job.room.name))
1. If participants disconnect or you want to cancel early: ◦
timer_task.cancel()
1. If you prefer automatic deletion without calling the API, set
RoomOptions(delete_room_on_close=True)
when creating/opening the room (then omit the explicit delete call). Cleanup hooks • Use
ctx.add_shutdown_callback()
to save state or run other cleanup; hooks run during shutdown (framework waits ~10s). If you’d like, I can: • Provide a full runnable example integrated into your handler, or • Show the exact
RoomOptions
usage for your framework. Which would you prefer?, with interactive elements