Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Marko Rauhamaa Newsgroups: comp.lang.python Subject: Re: asyncio - run coroutine in the background Date: Tue, 16 Feb 2016 19:12:12 +0200 Organization: A noiseless patient Spider Lines: 50 Message-ID: <87vb5ok2ab.fsf@elektro.pacujo.net> References: <8737sumpjl.fsf@elektro.pacujo.net> <87h9ha8lt0.fsf@jester.gateway.pace.com> <87d1rwpwo2.fsf@elektro.pacujo.net> <56c33d7e$0$1587$c3e8da3$5496439d@news.astraweb.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="b7cb1518d23ec19d482dcc9c31d30fdd"; logging-data="30835"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+xmhQXGq1Gu80XAnUmwHGC" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux) Cancel-Lock: sha1:TRttKGLk5q+kLHaLxGwwDJjLaeI= sha1:FgiVNOnoMjWcMl8e5Dp2iyEKMuc= Xref: csiph.com comp.lang.python:103018 Steven D'Aprano : > 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