R
R
Rudtoha2017-10-17 16:03:28
Python
Rudtoha, 2017-10-17 16:03:28

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()

Thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Dugin, 2017-10-25
@Rudtoha

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())

Also have a look here: Under what circumstances is closed afterwards in Python?

D
DarkMode, 2017-10-17
@DarkMode

import asyncio
import time

async def S():
    t = time.time()
    i = 0
    while time.time() - t < 1:
        i += 1
        loop.create_task(S())
    print("done")
loop = asyncio.get_event_loop()
cors = asyncio.wait([S()])
loop.run_until_complete(cors)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question