0

I have a function that I want to call every minute for instance and my code look like this:

async def fun1():
    print('fun1')
    await asyncio.sleep(30)

async def fun2():
    print('fun2')
    await asyncio.sleep(10)

async def fun3():
    print('fun3')

async def main():
    global loop

    loop.create_task(fun1())
    loop.create_task(fun2())

    while True:
        await fun3()
        await asyncio.sleep(1)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()    
    loop.run_until_complete(main())

but it does not print anything. I would like my function to be called every 10 seconds for instance. It looks like fun2 is waiting for fun1 to finish instead of triggering every 30 seconds and 10 seconds respectively... Any idea why pelase?

Nicolas Rey
  • 431
  • 2
  • 6
  • 19
  • It does not print anything either... – Nicolas Rey Sep 07 '20 at 21:09
  • `main` never yields control back to the event loop so `fun` never gets a chance to run. You'll need to await something that yields back inside your while loop, eg, `asyncio.sleep`. You'll also want to update `now`. – dirn Sep 07 '20 at 21:21

1 Answers1

0

Currently, fun1 and fun2 will only print once each since neither contain a loop. Add a loop to make them each print every 10/30 seconds.

import asyncio
async def fun1():
    while True:
        print('fun1')
        await asyncio.sleep(30)

async def fun2():
    while True:
        print('fun2')
        await asyncio.sleep(10)

async def fun3():
    print('fun3')

async def main():
    global loop

    loop.create_task(fun1())
    loop.create_task(fun2())

    while True:
        await fun3()
        await asyncio.sleep(1)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
SuperStormer
  • 4,997
  • 5
  • 25
  • 35