我有一个长时间运行的同步Python程序,我想每秒运行约10个“fire and forget”任务。这些任务会命中远程API,并且不需要返回任何值。我尝试了这个答案,但是它需要太多的CPU/内存来生成和维护所有单独的线程,所以我一直在研究asyncio。
这个答案很好地解释了如何使用asyncio运行“fire and forget”。然而,它需要使用
run_until_complete()
,这会等到所有的asyncio任务完成才会结束。我的程序正在使用同步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运行它?
fire_and_forget()
会在第一次调用时小心地创建/启动一个新线程。 - user4815162342