asyncio - run coroutine in the background

Marko Rauhamaa marko at pacujo.net
Tue Feb 16 12:14:18 EST 2016


Steven D'Aprano <steve at pearwood.info>:

> On Wed, 17 Feb 2016 01:17 am, Marko Rauhamaa wrote:
>
>> Ok, yes, but those "background tasks" monopolize the CPU once they are
>> scheduled to run.
>
> Can you show some code demonstrating this?

Sure:

========================================================================
#!/usr/bin/env python3

import asyncio, time

def main():
    asyncio.get_event_loop().run_until_complete(asyncio.wait([
        background_task(),
        looping_task() ]))

@asyncio.coroutine
def looping_task():
    while True:
        yield from asyncio.sleep(1)
        print(int(time.time()))

@asyncio.coroutine
def background_task():
    yield from asyncio.sleep(4)
    t = time.time()
    while time.time() - t < 10:
        pass

if __name__ == '__main__':
    main()
========================================================================

which prints:

   1455642629
   1455642630
   1455642631
   1455642642                <============== gap
   1455642643
   1455642644
   1455642645


Marko


More information about the Python-list mailing list