Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: "Frank Millman" Newsgroups: comp.lang.python Subject: Re: asyncio - how to stop background task cleanly Date: Sun, 7 Feb 2016 07:27:19 +0200 Lines: 36 Message-ID: References: <87lh6ys052.fsf@elektro.pacujo.net> <87fux5svhk.fsf@elektro.pacujo.net> <8737t5shhp.fsf@elektro.pacujo.net> 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 W3VZ+JpyJKQdFhhudx1j/wp9gf+vKh5QKFneEjvyJ4kw== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.012 X-Spam-Evidence: '*H*': 0.98; '*S*': 0.00; 'startup': 0.05; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'def': 0.13; 'async': 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:stop': 0.16; 'true:': 0.16; 'try:': 0.18; 'wrote': 0.23; 'specially': 0.23; 'thanks,': 0.24; 'header:In-Reply-To:1': 0.24; 'header:X-Complaints-To:1': 0.26; 'supported': 0.27; 'task': 0.30; 'url:python': 0.33; 'except': 0.34; 'should': 0.36; 'needed': 0.36; 'url:org': 0.36; 'url:library': 0.36; 'to:addr:python-list': 0.36; 'subject:: ': 0.37; 'thanks': 0.37; 'received:org': 0.37; 'to:addr:python.org': 0.40; 'url:3': 0.60; 'skip:a 40': 0.64; 'frank': 0.72; 'skip:n 40': 0.72; 'await': 0.76; 'actually,': 0.84; 'do:': 0.91 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: 197.89.92.138 In-Reply-To: <8737t5shhp.fsf@elektro.pacujo.net> 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:102608 "Marko Rauhamaa" wrote in message news:8737t5shhp.fsf@elektro.pacujo.net... > > > Actually, cancellation is specially supported in asyncio ( https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel>) > so this should do: > > async def background_task(): > while True: > await perform_task() > await asyncio.sleep(10) > That's exactly what I needed - thanks, Marko async def background_task() try: while True: await perform_task() await asyncio.sleep(10) except asyncio.CancelledError: await perform_cleanup() At startup - task = asyncio.ensure_future(background_task()) At shutdown - task.cancel() await asyncio.wait([task]) Works perfectly - thanks again. Frank