python - 如何永远运行异步函数(Python)
问题描述
如何使用 asyncio 并永远运行该功能。我知道有,run_until_complete(function_name)
但是如何使用run_forever
如何调用异步函数?
async def someFunction():
async with something as some_variable:
# do something
我不确定如何启动该功能。
解决方案
run_forever
并不意味着异步函数会神奇地永远运行,这意味着循环将永远运行,或者至少直到有人调用loop.stop()
. 要从字面上永远运行异步函数,您需要创建一个执行此操作的异步函数。例如:
async def some_function():
async with something as some_variable:
# do something
async def forever():
while True:
await some_function()
loop = asyncio.get_event_loop()
loop.run_until_complete(forever())
这就是为什么run_forever()
不接受参数,它不关心任何特定的协程。典型的模式是loop.create_task
在调用之前添加一些使用或等效的协程run_forever()
。但即使是一个不运行任何任务并且闲置的事件循环也很有用,因为另一个线程可以调用asyncio.run_coroutine_threadsafe
它并让它工作。
推荐阅读
- c++ - 为什么程序打印 0 而不是平均值?
- flutter - 当规则禁止除用户之外的任何人阅读时,检查 Firestore 用户是否存在
- php - “bridge”相等的一张表的输出
- python - 使用序列的 type() 作为类型保留映射的构造函数会产生“意外参数”警告
- autodesk-model-derivative - 获取单个 dbid 的属性无法返回数据状态 202
- f# - F# 中的类型与模块
- sql - 无法使用 SQL 中的触发器生成或更新表行
- typescript - 来自数据加载器的关系数据的 URQL GraphQL 缓存问题
- javascript - 如何将 chrome.storage 中的值分配给扩展变量
- c# - 使用 C# 获取管道 3D CAD 模型信息询问样条曲线