如何在后台运行无限循环?

use*_*341 3 python python-asyncio

我有一个持续监控 API 的函数。基本上,该函数获取数据,解析它,然后将其附加到文件中。然后它会等待 15 分钟并一遍又一遍地执行相同的操作。

我想要的是在后台运行这个循环,这样我就不会阻止其余代码的执行。

Tim*_*Tim 6

如果您正在使用 asyncio(我假设您是由于 asyncio 标签),则可以使用任务执行计划操作。

import asyncio

loop = asyncio.get_event_loop()

async def check_api():
    while True:
        # Do API check, helps if this is using async methods
        await asyncio.sleep(15 * 60)  # 15 minutes (in seconds)

loop.create_task(check_api())

...  # Rest of your application

loop.run_forever()
Run Code Online (Sandbox Code Playgroud)

如果您的 API 检查不是异步的(或者您用来与其交互的库不是异步的),您可以使用 Executor 在单独的线程或进程中运行操作,同时仍然维护 asyncio API。

例如:

from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor()

def call_api():
    ...

async def check_api():
    while True:
        await loop.run_in_executor(executor, call_api)
        await asyncio.sleep(15 * 60)  # 15 minutes (in seconds)
Run Code Online (Sandbox Code Playgroud)

请注意,asyncio 不会自动使您的代码并行,它是协作式多任务处理,您的所有方法都需要使用await 进行协作,长时间运行的操作仍然会阻塞其他线程,在这种情况下,Executor 会有所帮助。