在python中使用其他协程运行aio调度

kcwpcxri  于 2022-12-10  发布在  Python
关注(0)|答案(1)|浏览(121)

我有两个协程,其中一个使用aioschedule。这是我的代码

import aioschedule as schedule
import asyncio

async def foo():
    while True:
        print('foooooo')
        await asyncio.sleep(5)

async def bar():
    while True:
        print('bar')
        await asyncio.sleep(1)

schedule.every(2).seconds.do(bar)

loop = asyncio.get_event_loop()
loop.create_task(schedule.run_pending())
loop.create_task(foo())

try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.stop()

我想要的是它应该打印bar每n秒时,其他任务正在运行,但输出只有foooooo。我错过了什么?

efzxgjgh

efzxgjgh1#

试试这个:

import aioschedule as schedule
   import asyncio

   async def foo():
       while True:
           print('foooooo')
           await asyncio.sleep(5)

    async def bar():
        while True:
            print('bar')
            await asyncio.sleep(1)

    #schedule.every(2).seconds.do(bar) <---removed line

    loop = asyncio.get_event_loop()
    loop.create_task(schedule.run_pending())
    loop.create_task(foo())
    loop.create_task(bar()) #<---- added line

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.stop()

相关问题