from fastapi import FastAPI import asyncio app = FastAPI() user_sched = {} async def my_async_task(): # 这里是异步任务的代码 # 倒计时3秒 await asyncio.sleep(10) print("close") async def task_start(username, device): task = asyncio.create_task(my_async_task()) user_sched[username] = task @app.get("/video/{username}/{device}") async def startup(username, device): if username not in user_sched: await task_start(username, device) else: t = user_sched['1'] t.cancel() await task_start() if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8004)