Path: csiph.com!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:14:18 +0200 Organization: A noiseless patient Spider Lines: 50 Message-ID: <87mvr0k26t.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/tIX1oS+N+L+S0S2BgNhM+" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux) Cancel-Lock: sha1:kz0XJZOjGlq0cVkd8l89/hbucTw= sha1:WPU9XH0jxTrlp8WbQoFPx7pfNcQ= Xref: csiph.com comp.lang.python:103020 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