也许我理解错了,但这是我的问题。
正如我在纪录片中所读到的,您需要创建任务以同时执行它们:
async def main():
x=1
lastman = deque([])
while True:
task1 = asyncio.create_task(get_salt())
task2 = asyncio.create_taks(get_sugar_every10_secondes())
await task1
await task2
async def get_salt():
salt = await salt.fetch()
print(salt)
async def get_sugar_every10_secondes():
await asyncio.sleep(10)
sugar = await sugar.fetch()
print(sugar)
asyncio.get_even_loop().run_until_completed(main())
问题在于,我每10秒只能获得盐和糖的输出,但是我希望尽快盐分和每10秒输出糖。 (py3.7)
答案 0 :(得分:0)
while True:
# ...
await task1
await task2
这部分意思是:
在完成两项任务之前,不会重新创建任何任务。
相反,您应该创建两个任务,每个任务在while True
循环中调用自己的协程。这样,他们的noen就应该等了。
类似这样的东西:
import asyncio
from collections import deque
async def do_constantly(coro_func):
while True:
await coro_func()
async def get_salt():
await asyncio.sleep(1)
print('salt')
async def get_sugar_every10_secondes():
await asyncio.sleep(10)
print('sugar')
async def main():
task1 = asyncio.create_task(do_constantly(get_salt))
task2 = asyncio.create_task(do_constantly(get_sugar_every10_secondes))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.run_forever() # to keep tasks spawning