Free cookie consent management tool by TermsFeed cancelled() method of Task class in asyncio | Pythontic.com

Cancelled() method of Task class in asyncio

Overview:

  • For a task to be considered cancelled, the coroutine that is wrapped as the Task should have handled and propagated the asyncio.CancelledError.

  • The method cancelled() returns whether a Task has been cancelled or not.

  • The return value is True, if the Task has been cancelled successfully and False otherwise.

Example:

# Example Python program that cancels
# a scheduled/running task in the
# event loop provided by the asyncio
# module
import asyncio
import time
 
marketOpen = True

# A coroutine defintion of order bot
async def orderBot():
    try:
        global marketOpen
        while(marketOpen):
            print("Making orders...")
            await asyncio.sleep(1)
    except:
        # Handle the exception
        print("Stopping the bot")
        marketOpen = False
        # Propagate the exception
        raise 
    finally:
        # Cleanup
        marketOpen = False
        print("Bot stopped")

# Coroutine that creates the Task
async def console():
    bot = asyncio.create_task(orderBot())
    await asyncio.sleep(3)
    bot.cancel()


    try:
     await bot;
    except: 
        print("Console has stopped the bot")
    print("Task has been cancelled:%s"%bot.cancelled())        

# Create event loop
loop = asyncio.new_event_loop()

# Set the new loop object to asyncio
asyncio.set_event_loop(loop)

# Run the asyncio Task
asyncio.run(console())

Output:

Making orders...

Making orders...

Making orders...

Stopping the bot

Bot stopped

Console has stopped the bot

Task has been cancelled:True


Copyright 2025 © pythontic.com