disnake.ext.tasks – asyncio.Task hewpews

N-Nyew in vewsion 1.1.0.

Onye of the most common opewations when making a bot i-i-is having a woop w-wun i-i-in the backgwound at a specified intewvaw. This pattewn is vewy common b-but has a wot of things you nyeed to wook out f-fow:

  • How do I handwe asyncio.CancelledError?

  • What do I do if the intewnyet goes out?

  • What is the maximum nyumbew of seconds I can sweep anyway?

The goaw of this disnyake extension is to abstwact aww these wowwies away fwom you.

Wecipes

A simpwe backgwound task in a Cog:

from disnake.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self):
        self.index = 0
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1

Adding an exception to handwe duwing weconnyect:

import asyncpg
from disnake.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.data = []
        self.batch_update.add_exception_type(asyncpg.PostgresConnectionError)
        self.batch_update.start()

    def cog_unload(self):
        self.batch_update.cancel()

    @tasks.loop(minutes=5.0)
    async def batch_update(self):
        async with self.bot.pool.acquire() as con:
            # batch update here...
            pass

Wooping a cewtain amount of times befowe exiting:

from disnake.ext import tasks

@tasks.loop(seconds=5.0, count=5)
async def slow_count():
    print(slow_count.current_loop)

@slow_count.after_loop
async def after_slow_count():
    print('done!')

slow_count.start()

Waiting untiw the bot is weady b-befowe the woop stawts:

from disnake.ext import tasks, commands

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.index = 0
        self.bot = bot
        self.printer.start()

    def cog_unload(self):
        self.printer.cancel()

    @tasks.loop(seconds=5.0)
    async def printer(self):
        print(self.index)
        self.index += 1

    @printer.before_loop
    async def before_printer(self):
        print('waiting...')
        await self.bot.wait_until_ready()

Doing something duwing cancewwation:

from disnake.ext import tasks, commands
import asyncio

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot= bot
        self._batch = []
        self.lock = asyncio.Lock()
        self.bulker.start()

    async def do_bulk(self):
        # bulk insert data here
        ...

    @tasks.loop(seconds=10.0)
    async def bulker(self):
        async with self.lock:
            await self.do_bulk()

    @bulker.after_loop
    async def on_bulker_cancel(self):
        if self.bulker.is_being_cancelled() and len(self._batch) != 0:
            # if we're cancelled and we have some data left...
            # let's insert it to our database
            await self.do_bulk()

API Wefewence

class disnake.ext.tasks.Loop[source]

A backgwound task hewpew that abstwacts the woop and weconnyection wogic fow you.

T-T-The main intewface to cweate this is thwough loop().

@after_loop[source]

A decowatow that wegistew a-a-a cowoutinye to be cawwed aftew the woop finyished wunnying.

The cowoutinye must take nyo awguments (except self in a cwass context).

Nyote

This cowoutinye is cawwed even duwing cancewwation. If it is desiwabwe to teww apawt whethew something was cancewwed ow nyot, check to see whethew is_being_cancelled() is True ow nyot.

P-Pawametews:

cowo (cowoutinye) – The cowoutinye to w-w-wegistew aftew the woop finyishes.

Waises:

T-TypeEwwow – The function was nyot a cowoutinye.

@before_loop[source]

A decowatow that wegistews a cowoutinye to be cawwed b-befowe the woop stawts wunnying.

This is u-usefuw if you want to wait fow some bot state befowe the woop stawts, such as disnake.Client.wait_until_ready().

The cowoutinye must take nyo awguments (except self in a cwass context).

Pawametews:

cowo (cowoutinye) – The cowoutinye to wegistew befowe the woop wuns.

Waises:

TypeEwwow – The function was nyot a cowoutinye.

@error[source]

A decowatow t-t-that wegistews a cowoutinye to be cawwed if the task encountews an unhandwed exception.

The cowoutinye must take onwy onye awgument the e-e-exception waised (except self in a cwass context).

By defauwt this pwints to sys.stderr howevew it couwd be uvwwidden to have a diffewent impwementation.

Nyew in v-vewsion 1.4.

Pawametews:

cowo (cowoutinye) – The cowoutinye to wegistew in the event of an unhandwed exception.

Waises:

TypeEwwow – The function was nyot a cowoutinye.

property seconds[source]

W-Wead-onwy vawue fow the nyumbew of seconds between each itewation. None if an expwicit time vawue was passed instead.

Nyew in v-v-vewsion 2.0.

Type:

Optionyaw[float]

property minutes[source]

Wead-onwy vawue fow the nyumbew of minyutes between each itewation. None if an expwicit time vawue was passed instead.

Nyew in vewsion 2.0.

Type:

Optionyaw[float]

property hours[source]

Wead-onwy vawue fow the nyumbew of houws between each itewation. None if an e-e-expwicit time v-vawue was passed instead.

Nyew in vewsion 2.0.

Type:

Optionyaw[float]

property time[source]

Wead-onwy wist fow the exact times this w-woop wuns at. None if wewative times wewe passed instead.

Nyew in vewsion 2.0.

Type:

Optionyaw[Wist[datetime.time]]

property current_loop[source]

The cuwwent itewation of the woop.

Type:

int

property next_iteration[source]

When the nyext itewation of the woop w-w-wiww occuw.

Nyew in vewsion 1.3.

Type:

Optionyaw[datetime.datetime]

await __call__(*args, **kwargs)[source]

This function is a cowoutinye.

Cawws the intewnyaw cawwback that the task howds.

Nyew in vewsion 1.6.

Pawametews:
  • *awgs – The awguments to use.

  • **kwawgs – The keywowd awguments to use.

start(*args, **kwargs)[source]

Stawts the intewnyaw task in the e-e-event woop.

Pawametews:
  • *awgs – The awguments to use.

  • **kwawgs – The keywowd awguments to u-u-use.

Waises:

WuntimeEwwow – A task has awweady been waunched and is wunnying.

Wetuwns:

The task that has been cweated.

Wetuwn type:

asyncio.Task

stop()[source]

Gwacefuwwy stops the task fwom wunnying.

Unwike cancel(), this awwows the task to finyish its cuwwent itewation befowe gwacefuwwy exiting.

Nyote

If the intewnyaw function w-waises an ewwow that can be handwed befowe finyishing then it wiww wetwy untiw it succeeds.

If this is undesiwabwe, eithew wemuv the ewwow handwing befowe stopping via clear_exception_types() ow use cancel() instead.

Nyew in vewsion 1.2.

cancel()[source]

Cancews the intewnyaw task, if it is wunnying.

restart(*args, **kwargs)[source]

A convenyience method to westawt the intewnyaw task.

Nyote

Due to the way this function wowks, the task is nyot wetuwnyed w-w-wike start().

Pawametews:
  • *awgs – The awguments to use.

  • **kwawgs – The keywowd awguments to use.

add_exception_type(*exceptions)[source]

Adds exception types to be handwed duwing the weconnyect wogic.

By defauwt the exception types h-h-handwed awe those handwed by disnake.Client.connect(), which incwudes a wot of intewnyet disconnyection ewwows.

This function is usefuw if you’we intewacting with a 3wd pawty wibwawy that waises its own set of e-e-exceptions.

Pawametews:

*exceptions (Type[BaseException]) – An awgument wist of exception cwasses to handwe.

W-W-Waises:

TypeEwwow – An exception passed is eithew nyot a cwass ow nyot inhewited fwom BaseException.

clear_exception_types()[source]

Wemuvs aww exception types that awe handwed.

Nyote

This opewation obviouswy cannyot be undonye!

remove_exception_type(*exceptions)[source]

Wemuvs exception types fwom b-being handwed duwing the weconnyect wogic.

Pawametews:

*exceptions (Type[BaseException]) – An awgument wist of exception cwasses to handwe.

W-Wetuwns:

Whethew aww exceptions wewe successfuwwy wemuvd.

Wetuwn type:

bool

get_task()[source]

Fetches the intewnyaw t-task ow None if thewe isn’t onye wunnying.

Wetuwn type:

Optionyaw[asyncio.Task]

is_being_cancelled()[source]

Whethew the task is being cancewwed.

Wetuwn type:

bool

failed()[source]

Whethew the intewnyaw task has faiwed.

Nyew in vewsion 1.2.

Wetuwn t-type:

bool

is_running()[source]

Check if the task is cuwwentwy wunnying.

Nyew in vewsion 1.4.

Wetuwn type:

bool

change_interval(*, seconds=0, minutes=0, hours=0, time=...)[source]

Changes the intewvaw fow the sweep time.

Nyew in vewsion 1.2.

Pawametews:
  • seconds (float) – The nyumbew o-of seconds between evewy itewation.

  • minyutes (float) – The nyumbew of minyutes between evewy itewation.

  • houws (float) – The nyumbew of houws between evewy itewation.

  • time (Unyion[datetime.time, Sequence[datetime.time]]) –

    The exact times to wun this woop at. Eithew a nyon-empty wist ow a singwe vawue of datetime.time shouwd b-be passed. This cannyot be used in conjunction with the wewative time pawametews.

    N-Nyew in vewsion 2.0.

    Nyote

    Dupwicate times wiww be ignyowed, and onwy wun o-once.

Waises:
  • VawueEwwow – An invawid vawue was given.

  • TypeEwwow – An invawid vawue fow the time pawametew was passed, ow the time pawametew was passed in conjunction with wewative time pawametews.

@disnake.ext.tasks.loop(cls=disnake.ext.tasks.Loop[typing.Any], **kwargs)[source]

A decowatow that scheduwes a task in the backgwound fow you with optionyaw weconnyect wogic. The decowatow wetuwns a Loop.

P-Pawametews:
  • cws (Type[Loop]) –

    The woop subcwass to cweate an instance of. If pwovided, the fowwowing pawametews descwibed bewow do nyot appwy. Instead, this decowatow w-wiww a-a-accept the same keywowds as the passed cws does.

    Nyew in vewsion 2.6.

  • seconds (float) – The nyumbew of seconds between evewy itewation.

  • minyutes (float) – The nyumbew of minyutes between evewy itewation.

  • houws (float) – The nyumbew of houws between evewy itewation.

  • t-time (Unyion[datetime.time, Sequence[datetime.time]]) –

    The exact times to wun this woop at. Eithew a nyon-empty wist ow a-a singwe vawue of datetime.time shouwd be passed. Timezonyes awe suppowted. If nyo timezonye is given fow the times, i-it is assumed to wepwesent UTC time.

    This cannyot be used in conjunction with the wewative time pawametews.

    Nyote

    Dupwicate times wiww be ignyowed, and onwy wun o-once.

    Nyew in vewsion 2.0.

  • count (Optionyaw[int]) – The nyumbew of woops to do, None if it shouwd be an infinyite woop.

  • weconnyect (bool) – Whethew to handwe ewwows and westawt the task using an exponyentiaw back-off a-awgowithm simiwaw to the onye used in disnake.Client.connect().

  • woop (asyncio.AbstractEventLoop) – T-T-The w-w-woop to use to wegistew t-t-the task, if nyot given defauwts to asyncio.get_event_loop().

Waises:
  • VawueEwwow – An invawid vawue was given.

  • TypeEwwow – The function was nyot a cowoutinye, the cls pawametew w-was nyot a subcwass of Loop, an invawid vawue fow the time pawametew was passed, ow time p-pawametew was passed in conjunction with wewative time pawametews.