【发布时间】:2020-07-27 03:52:20
【问题描述】:
我有一个长时间运行的同步 Python 程序,我希望每秒运行大约 10 个“即发即弃”的任务。这些任务命中远程 API,不需要返回任何值。我尝试了this answer,但它需要太多的 CPU/内存来生成和维护所有单独的线程,所以我一直在研究 asyncio。
This answer 很好地解释了如何使用 asyncio 运行“一劳永逸”。但是,它需要使用run_until_complete(),它会等待所有异步任务完成。我的程序正在使用同步 Python,所以这对我不起作用。理想情况下,代码应该像这样简单,log_remote 不会阻塞循环:
while True:
latest_state, metrics = expensive_function(latest_state)
log_remote(metrics) # <-- this should be run as "fire and forget"
我使用的是 Python 3.7。如何在另一个线程上使用 asyncio 轻松运行它?
【问题讨论】:
标签: python multithreading python-asyncio fire-and-forget