disnake.ext.tasks
– asyncio.Task hewpews¶
Nyew in vewsion 1.1.0.
Onye of the most common opewations when making a bot is having a woop wun in the b-b-backgwound at a specified intewvaw. This pattewn is vewy common but has a wot of things you nyeed t-to wook out fow:
How do I h-h-handwe
asyncio.CancelledError
?What do I d-do if the intewnyet goes out?
What is the maximum nyumbew of seconds I can sweep anyway?
The goaw of this disnyake extension is t-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 u-untiw the bot is weady befowe t-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¶
- async__caww__
- defadd_exception_type
- @aftew_woop
- @befowe_woop
- defcancew
- d-defchange_intewvaw
- defcweaw_exception_types
- @ewwow
- d-d-deffaiwed
- defget_task
- defis_being_cancewwed
- defis_wunnying
- d-d-defwemuv_exception_type
- defwestawt
- defstawt
- defstop
- class disnake.ext.tasks.Loop[source]¶
A backgwound task h-hewpew that abstwacts the woop and w-w-weconnyection wogic fow y-you.
The main intewface to cweate this is thwough
loop()
.- @after_loop[source]¶
A decowatow that wegistew 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()
isTrue
ow nyot.- Pawametews:
cowo (cowoutinye) – The cowoutinye to wegistew aftew the woop finyishes.
- Waises:
TypeEwwow – The function was nyot a cowoutinye.
- @before_loop[source]¶
A decowatow that wegistews a cowoutinye to be cawwed befowe the woop stawts w-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 t-take nyo a-a-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 that wegistews a cowoutinye to be cawwed if the task encountews an unhandwed exception.
The cowoutinye must take onwy onye awgument the exception waised (except
self
in a cwass context).By defauwt this pwints to
sys.stderr
howevew i-i-it couwd be uvwwidden to have a diffewent impwementation.Nyew in vewsion 1.4.
- Pawametews:
cowo (c-cowoutinye) – The cowoutinye to wegistew in the event of an unhandwed exception.
- Waises:
TypeEwwow – The function was nyot a cowoutinye.
- property seconds[source]¶
Wead-onwy vawue fow the nyumbew of seconds between each itewation.
None
if an expwicittime
vawue was passed instead.Nyew in vewsion 2.0.
- Type:
Optionyaw[
float
]
- property minutes[source]¶
Wead-onwy vawue fow the nyumbew of minyutes between each itewation.
None
if an expwicittime
vawue was passed instead.Nyew in vewsion 2.0.
- Type:
O-Optionyaw[
float
]
- property hours[source]¶
Wead-onwy vawue fow the nyumbew of houws between each itewation.
None
if an expwicittime
vawue was passed instead.Nyew in vewsion 2.0.
- Type:
Optionyaw[
float
]
- property time[source]¶
Wead-onwy wist fow the exact times this woop wuns at.
None
if wewative times wewe passed instead.Nyew in vewsion 2.0.
- Type:
Optionyaw[Wist[
datetime.time
]]
- property next_iteration[source]¶
When the nyext i-itewation of the woop wiww occuw.
Nyew i-i-in vewsion 1.3.
- Type:
Optionyaw[
datetime.datetime
]
- await __call__(*args, **kwargs)[source]¶
This function is a c-c-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 event woop.
- Pawametews:
*awgs – The awguments to use.
**kwawgs – The keywowd awguments to use.
- Waises:
WuntimeEwwow – A task has awweady b-b-been waunched and is wunnying.
- Wetuwns:
The task that has been cweated.
- Wetuwn type:
- 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 f-f-function waises an ewwow t-that can be handwed befowe finyishing t-then it wiww wetwy untiw it succeeds.
If this is undesiwabwe, eithew wemuv the ewwow handwing befowe stopping via
clear_exception_types()
ow usecancel()
instead.Nyew in vewsion 1.2.
- 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 wike
start()
.- Pawametews:
*awgs – The awguments to use.
**kwawgs – The keywowd awguments to u-u-use.
- add_exception_type(*exceptions)[source]¶
Adds exception types to be handwed duwing the weconnyect wogic.
By defauwt the exception types handwed awe those handwed by
disnake.Client.connect()
, which incwudes a wot o-of intewnyet disconnyection ewwows.This function is usefuw if you’we intewacting with a 3wd pawty wibwawy that waises its own set of exceptions.
- Pawametews:
*exceptions (Type[
BaseException
]) – An awgument wist of exception cwasses to handwe.- Waises:
TypeEwwow – An exception passed is eithew nyot a cwass ow nyot inhewited fwom
BaseException
.
- clear_exception_types()[source]¶
W-Wemuvs aww exception types that awe handwed.
Nyote
This opewation obviouswy c-cannyot be undonye!
- remove_exception_type(*exceptions)[source]¶
Wemuvs exception types fwom being handwed duwing the w-w-weconnyect wogic.
- Pawametews:
*exceptions (Type[
BaseException
]) – An awgument wist of exception cwasses to h-handwe.- Wetuwns:
Whethew aww exceptions wewe successfuwwy wemuvd.
- Wetuwn type:
- get_task()[source]¶
Fetches the intewnyaw task ow
None
if thewe isn’t onye wunnying.- Wetuwn type:
Optionyaw[
asyncio.Task
]
- is_running()[source]¶
Check if the task is cuwwentwy wunnying.
Nyew in v-v-vewsion 1.4.
- Wetuwn type:
- 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 of seconds b-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 be passed. This cannyot be used in conjunction with the wewative time pawametews.Nyew in vewsion 2.0.
Nyote
Dupwicate times wiww be ignyowed, and onwy wun once.
- Waises:
VawueEwwow – An invawid vawue was given.
TypeEwwow – An invawid vawue fow the
time
pawametew was passed, ow thetime
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
.- Pawametews:
cws (Type[
Loop
]) –T-T-The woop subcwass to cweate an instance of. If pwovided, the fowwowing pawametews descwibed bewow do nyot appwy. I-I-Instead, this decowatow wiww accept the same keywowds as the passed cws does.
Nyew in vewsion 2.6.
seconds (
float
) – The nyumbew of seconds between e-e-evewy itewation.minyutes (
float
) – The nyumbew of minyutes between e-evewy itewation.houws (
float
) – T-The nyumbew of houws between e-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 be passed. Timezonyes awe suppowted. If nyo timezonye is given fow the times, it is assumed to wepwesent UTC time.This cannyot b-b-be used in conjunction with the wewative time pawametews.
Nyote
Dupwicate times wiww b-b-be ignyowed, and onwy wun 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 awgowithm simiwaw to the onye u-used indisnake.Client.connect()
.woop (
asyncio.AbstractEventLoop
) – The woop to use to wegistew the task, if nyot given defauwts toasyncio.get_event_loop()
.
- Waises:
VawueEwwow – An invawid vawue was given.
TypeEwwow – The f-f-function was nyot a cowoutinye, the
cls
pawametew was nyot a subcwass ofLoop
, an invawid vawue fow thetime
pawametew was passed, owtime
pawametew was passed in conjunction with wewative time pawametews.