Answer the question
In order to leave comments, you need to log in
How to make event loop perform the same task indefinitely?
Hello, just started to deal with the Asyncio module, and a problem arose: there is a certain asynchronous function that does something. I wrap it in create_task and send it to the event loop. But the task is executed only once, despite the fact that I set the run_forever parameter to the loop.
For clarity, the code:
import asyncio
import time
async def S():
t = time.time()
i = 0
while time.time() - t < 5:
i += 1
print("done")
loop = asyncio.get_event_loop()
loop.create_task(S())
loop.run_forever()
loop.close()
Answer the question
In order to leave comments, you need to log in
You don't have a function that requires I/O to wait, so asyncio is not needed. But here is an example template:
import asyncio
from contextlib import closing
async def get_some_data():
# Обработка I/O - например, получение данных через HTTP
await asyncio.sleep(2)
data = 'ping'
print(data)
return data
async def process(data):
# Обработка данных на CPU
await asyncio.sleep(1)
print('pong')
async def main():
while True:
data = await get_some_data() # Блокирующий вызов - ожидание поступления новой порции данных
asyncio.ensure_future(process(data)) # Неблокирующий вызов - обработка данных на CPU
if __name__ == "__main__":
with closing(asyncio.get_event_loop()) as event_loop:
event_loop.run_until_complete(main())
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question