使用 python asyncio 运行后台任务

问题描述 投票:0回答:1

我正在构建一个 websocket 服务器,我希望在其中有一个后台任务,该任务从 SQS 接收消息并将它们发送到客户端,同时不阻止其余事件。

但是当我使用 uvicorn 运行服务器时,我不断收到此错误

RuntimeWarning: coroutine 'background_task' was never awaited.

如何才能使其连续向客户端发送数据而不阻塞其余事件?

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()
python websocket socket.io python-asyncio python-socketio
1个回答
0
投票

import asyncio
添加到您的导入中,并将线程创建行更改为:

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

(注意双括号和结尾的逗号)。

如果它是异步函数,它必须在异步循环中运行 -

asyncio.run
是创建默认循环并执行协同例程的便捷快捷方式,已经在进程中“等待”它。

© www.soinside.com 2019 - 2024. All rights reserved.