我使用夸脱创建了一个应用程序,它有一个后台任务,执行数据分析和编写报告等任务。当我用ctrl-c结束应用程序时,后台线程立即被杀死,即使它处于IO任务的中间,如何让框架等待后台任务完成呢?
更新:我最初的实现是使用run()执行线程,因为异步支持创建任务(create_task),所以我试图摆脱这种情况,这似乎是更好的方法,尽管我不知道。
class Application:
def __init__(self):
self._is_initialised : bool = False
self._shutdown_completed : bool = False
self._shutdown_requested : bool = False
async def run(self) -> None:
while not self._shutdown_requested and self._is_initialised:
try:
await self._main_loop()
await asyncio.sleep(0.1)
except KeyboardInterrupt:
break
self._shutdown_completed = True
def stop(self) -> None:
print("Shutting down...")
self._shutdown_requested = True
print('Shutdown has completed')
import asyncio
from quart import Quart
app = Quart(__name__)
SERVICE_APP = None
@app.before_serving
async def startup() -> None:
asyncio.create_task(SERVICE_APP.run())
@app.after_serving
async def shutdown() -> None:
SERVICE_APP.stop()
SERVICE_APP = Application(app)
发布于 2022-08-16 14:55:12
在这里,背景任务可能是更好的选择,因为夸脱将延迟关机(只要ASGI服务器允许),同时等待后台任务停止,见文档
from quart import Quart
app = Quart(__name__)
async def background_task():
# Actual code to run in the background
@app.before_serving
async def startup() -> None:
app.add_background_task(background_task)
https://stackoverflow.com/questions/73372257
复制相似问题