diff options
| author | Rapptz <[email protected]> | 2019-05-10 18:36:19 -0400 |
|---|---|---|
| committer | Rapptz <[email protected]> | 2019-05-10 18:37:37 -0400 |
| commit | 47808a7e96da8028261fce0c06f841acb964d13a (patch) | |
| tree | b8f66949003baf47affb6c1aceaa893833472df6 | |
| parent | Minor nits in Discord Converters section of the docs. (diff) | |
| download | discord.py-47808a7e96da8028261fce0c06f841acb964d13a.tar.xz discord.py-47808a7e96da8028261fce0c06f841acb964d13a.zip | |
[tasks] Add Loop.restart
This implementation waits until the task is done before starting it
again.
Closes #2075
| -rw-r--r-- | discord/ext/tasks/__init__.py | 29 |
1 files changed, 28 insertions, 1 deletions
diff --git a/discord/ext/tasks/__init__.py b/discord/ext/tasks/__init__.py index 44194917..35d90d63 100644 --- a/discord/ext/tasks/__init__.py +++ b/discord/ext/tasks/__init__.py @@ -128,9 +128,36 @@ class Loop: self._task = self.loop.create_task(self._loop(*args, **kwargs)) return self._task + def _can_be_cancelled(self): + return not self._is_being_cancelled and self._task and not self._task.done() + def cancel(self): """Cancels the internal task, if it is running.""" - if not self._is_being_cancelled and self._task and not self._task.done(): + if self._can_be_cancelled(): + self._task.cancel() + + def restart(self, *args, **kwargs): + r"""A convenience method to restart the internal start. + + .. note:: + + Due to the way this function works, the task is not + returned like :meth:`start`. + + Parameters + ------------ + \*args + The arguments to to use. + \*\*kwargs + The keyword arguments to use. + """ + + def restart_when_over(fut, *, args=args, kwargs=kwargs): + self._task.remove_done_callback(restart_when_over) + self.start(*args, **kwargs) + + if self._can_be_cancelled(): + self._task.add_done_callback(restart_when_over) self._task.cancel() def add_exception_type(self, exc): |