TransWikia.com

Как в Aiogram запустить две функции одновременно

Stack Overflow на русском Asked on February 11, 2021

@dp.message_handler(Text('e'))
async def experiment(message: Message, state: FSMContext):
    tasks = [first(), second()]
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:  # if cleanup: 'RuntimeError: There is no current event loop..'
        loop = None

    if loop and loop.is_running():
        print('Async event loop already running')
        tsk = loop.create_task(tasks)
        # ^-- https://docs.python.org/3/library/asyncio-task.html#task-object
        tsk.add_done_callback(  # optional
            lambda t: print(f'Task done: '  # optional
                            f'{t.result()=} << return val of main()'))  # optional (using py38)
    else:
        print('Starting new event loop')
        asyncio.create(tasks)


def first():
    for i in range(10):
        print(1)
        asyncio.sleep(0.5)


def second(): #
    for i in range(10):
        print(2)
        asyncio.sleep(1)

One Answer

Сам разобрался

async def first():
    for i in range(10):
        print(1)
        await asyncio.sleep(0.5)
    return 'first'


async def second():
    for i in range(10):
        print(2)
        await asyncio.sleep(1)
    return 'second'


@dp.message_handler(Text('e'))
async def experiment(message: Message):
   
    loop = asyncio.get_running_loop()#Подключемся к действующему циклу
    tsk1 = loop.create_task(first())
    tsk2 = loop.create_task(second())
    tsk1.add_done_callback(lambda t: print(f'Task done: {t.result()} << return val of first task'))
    tsk2.add_done_callback(lambda t: print(f'Task done: {t.result()} << return val of second task'))

Answered by Дмитрий Бовак on February 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP