如何使用 asyncio 并永远运行该函数。我知道有 run_until_complete(function_name)
但如何使用 run_forever
如何调用异步函数?
async def someFunction():
async with something as some_variable:
# do something
我不确定如何启动该功能。
最佳答案
run_forever
并不意味着异步函数将神奇地永远运行,它意味着 loop 将永远运行,或者至少直到有人调用 loop .停止()
。要从字面上永远运行一个异步函数,您需要创建一个执行此操作的异步函数。例如:
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
并给它工作。
https://stackoverflow.com/questions/50473113/
相关文章:
wordpress - 使用 AWS RDS 和我自己的数据库哪个最便宜?
python - 自定义转换器和 GridSearch - 管道中的 ValueError
python - 使用 bigquery tables GET api 获取表的最后修改日期
ansible - 例如,如何限制 Ansible 的设置模块 (gather_facts) 仅检索
ruby-on-rails - 提交 Rails 的 credentials.yml.enc 文件是
intellij-idea - IntelliJ IDEA - 在路径中查找被锁定在另一个窗口监视器