Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: "Frank Millman" Newsgroups: comp.lang.python Subject: asyncio - run coroutine in the background Date: Mon, 15 Feb 2016 08:35:16 +0200 Lines: 41 Message-ID: Mime-Version: 1.0 Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original Content-Transfer-Encoding: 7bit X-Trace: news.uni-berlin.de K/xMocrGI8hIdaqYwAM86wZc4aeDXTBes1gJaRbNsMOg== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'args': 0.04; 'none:': 0.05; 'args,': 0.09; 'callback': 0.09; 'loop.': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'def': 0.13; 'skip:f 30': 0.15; '...)': 0.16; 'async': 0.16; 'background,': 0.16; 'callback)': 0.16; 'received:80.91.229.3': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'subject:run': 0.16; 'background.': 0.20; 'header:X-Complaints-To:1': 0.26; 'function': 0.28; 'run': 0.33; 'class': 0.33; 'but': 0.36; 'there': 0.36; 'to:addr:python-list': 0.36; 'received:org': 0.37; 'subject:the': 0.39; 'to:addr:python.org': 0.40; 'some': 0.40; 'waiting': 0.60; 'hope': 0.61; 'times': 0.63; 'frank': 0.72; 'await': 0.76; 'interest.': 0.79; 'task,': 0.91 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: 197.89.92.141 X-MSMail-Priority: Normal Importance: Normal X-Newsreader: Microsoft Windows Live Mail 15.4.3502.922 X-MimeOLE: Produced By Microsoft MimeOLE V15.4.3502.922 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.21rc2 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:102941 Hi all Using asyncio, there are times when I want to execute a coroutine which is time-consuming. I do not need the result immediately, and I do not want to block the current task, so I want to run it in the background. run_in_executor() can run an arbitrary function in the background, but a coroutine needs an event loop. After some experimenting I came up with this - class BackgroundTask: async def run(self, coro, args, callback=None): loop = asyncio.get_event_loop() loop.run_in_executor(None, self.task_runner, coro, args, callback) def task_runner(self, coro, args, callback): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) fut = asyncio.ensure_future(coro(*args)) if callback is not None: fut.add_done_callback(callback) loop.run_until_complete(fut) loop.close() Usage - bg_task = BackgroundTask() args = (arg1, arg2 ...) callback = my_callback_function await bg_task.run(coro, args, callback) Although it 'awaits' bk_task.run(), it returns immediately, as it is simply waiting for run_in_executor() to be launched. Hope this is of some interest. Frank Millman