Running a background task with python asyncio

127 views Asked by At

I am building a websocket server in which I want to have a background task that receives messages from SQS and sends them to client while not blocking rest of the events.

But I keep getting this error, when I run the server with uvicorn RuntimeWarning: coroutine 'background_task' was never awaited.

How can I make this send data to clients continuously without blocking the rest of the events?

import socketio
import threading
import json
from sqs_handler import SQSQueue

sio = socketio.AsyncServer(async_mode='asgi')
app = socketio.ASGIApp(sio, static_files={"/": "./"})

@sio.event
async def connect(sid, environ):
    print(sid, "connected")

@sio.event
async def disconnect(sid):
    print(sid, "disconnected")


@sio.event
async def item_removed(sid, data):

    await sio.emit("item_removed", data)


async def background_task():
    queue = SQSQueue()
    while True:
        message = queue.get_next_message_from_sqs()
        data = json.loads(message.body)
        await sio.emit('item_added', data)

background_thread = threading.Thread(target=background_task)
background_thread.daemon = True
background_thread.start()
1

There are 1 answers

0
jsbueno On

Add import asyncio to your imports, and change the thread creation line to:

background_thread = threading.Thread(target=asyncio.run, args=(background_task,))

(Pay attention to the double parenthesis and trailing comma).

If it is an async function, it must run in an async loop - asyncio.run is the convenient shortcut to create a default loop and execute a co-routine, already "awaiting" it in the process.