小编Арс*_*чко的帖子

在 Python FastAPI 应用程序中启动异步后台守护进程

我正在使用 FastAPI 为分析系统构建异步后端。问题是它必须: a) 侦听 API 调用并始终可用;b) 定期执行数据收集任务(解析数据并将其保存到数据库中)。

我编写了这个函数来充当守护进程:

    async def start_metering_daemon(self) -> None:
        """sets a never ending task for metering"""
        while True:
            delay: int = self._get_delay()  # delay in seconds until next execution
            await asyncio.sleep(delay)
            await self.gather_meterings()  # perfom data gathering
Run Code Online (Sandbox Code Playgroud)

我想要实现的是,当应用程序启动时,它还会将此守护程序函数添加到主事件循环中,并在有时间时执行它。然而,我一直无法找到适合任务规模的合适解决方案(添加芹菜和类似的东西是一种矫枉过正)。

我尝试过以下方法来实现这一目标,但没有一个有效:

@app.on_event("startup")
async def startup_event() -> None:
    """tasks to do at server startup"""
    await Gatherer().start_metering_daemon()
Run Code Online (Sandbox Code Playgroud)

结果:由于线程被阻塞,服务器无法启动

@app.on_event("startup")
async def startup_event() -> None:
    """tasks to do at server startup"""
    fastapi.BackgroundTasks().add_task(Gatherer().start_metering_daemon)
Run Code Online (Sandbox Code Playgroud)

结果:如日志中观察到的,任务从未执行

@app.on_event("startup")
async def startup_event() -> None:
    """tasks …
Run Code Online (Sandbox Code Playgroud)

python async-await python-asyncio fastapi

14
推荐指数
1
解决办法
7295
查看次数

标签 统计

async-await ×1

fastapi ×1

python ×1

python-asyncio ×1