Routines¶
- @after_routine
- @before_routine
- defcancel
- defchange_interval
- @error
- defnext_iteration
- asyncon_error
- defrestart
- defstart
- defstop
- class twitchio.ext.routines.Routine(*, name: str | None = None, coro: Callable[[...], Coroutine[Any, Any, Any]], max_attempts: int | None = None, iterations: int | None, wait_remainder: bool = False, stop_on_error: bool = False, wait_first: bool, time: datetime.datetime | None, delta: datetime.timedelta | None)¶
The TwitchIO Routine class which runs asynchronously in the background on a timed loop.
Note
You should not instantiate this class manually, instead use the
routine()decorator instead.Examples
# This routine will run every minute until stopped or canceled. @routines.routine(delta=datetime.timedelta(minutes=1)) async def my_routine() -> None: print("Hello World!") my_routine.start()
# Pass some arguments to a routine... @routines.routine(delta=datetime.timedelta(minutes=1)) async def my_routine(hello: str) -> None: print(f"Hello {hello}") my_routine.start("World!")
# Only run the routine three of times... @routines.routine(delta=datetime.timedelta(minutes=1), iterations=3) async def my_routine(hello: str) -> None: print(f"Hello {hello}") my_routine.start("World!")
- property args: tuple[Any, ...]¶
Property returning any positional arguments passed to the routine via
start().
- start(*args: Any, **kwargs: Any) Task[None]¶
Method to start the
Routinein the background.Note
You can not start an already running task. See:
restart()instead.- Parameters
- Returns
The internal background task associated with this
Routine.- Return type
- stop() None¶
Method to stop the currently running task after it completes its current iteration.
Unlike
cancel()this will schedule the task to stop after it completes its next iteration.
- cancel() None¶
Method to immediately cancel the currently running
Routine.Unlike
stop(), this method is not graceful and will cancel the task in its current iteration.
- restart(*, force: bool = True) None¶
Method which restarts the
Routine.If the
Routinehas not yet been started, this method immediately returns.
- before_routine(func: Callable[[...], Coroutine[Any, Any, Any]]) None¶
This function is a decorator.
Decorator used to set a coroutine to run before the
Routinehas started.Any arguments passed to
start()will also be passed to this coroutine callback.
- after_routine(func: Callable[[...], Coroutine[Any, Any, Any]]) None¶
This function is a decorator.
Decorator used to set a coroutine to run after the
Routinehas been stopped, canceled or completed.Any arguments passed to
start()will also be passed to this coroutine callback.
- async on_error(error: Exception) None¶
This function is a coroutine.
Default error handler for this
Routine. You can override this with theerror()decorator.By default this handler will log the exception.
- Parameters
error (Exception) – The exception raised in the routine.
- error(func: Callable[[...], Coroutine[Any, Any, Any]]) None¶
This function is a decorator.
Decorator used to set a coroutine as an error handler for this
Routine.
- property completed_iterations: int¶
Property returning a
intof the successfully completed iterations.Note
Iterations where an error occured do not count towards completed iterations.
- property remaining_iterations: int | None¶
Property returning a
intorNoneof the remaining iterations.If
iterationswas not set this returnsNone.
- property last_iteration: datetime.datetime | None¶
Property which returns a
datetime.datetimeof when the current iteration started.
- next_iteration() float¶
Method which returns the time until the next iteration as a float of seconds.
- change_interval(*, delta: datetime.timedelta | None = None, time: datetime.datetime | None = None, wait_first: bool = False) None¶
Method to change the running interval of a currently running routine.
- Parameters
delta (datetime.timedelta | None) – A
datetime.timedeltaof time to wait per iteration of theRoutine. If this isNone, you must pass thetimeparameter. Defaults toNone.time (datetime.datetime | None) – A
datetime.datetimeto schedule an run each iteration of theRoutine. TheRoutinewill run at the same time everyday. If this isNone, you must pass thedeltaparameter. Defaults toNone.wait_first (bool) – An optional
boolindicating whether the currently running routine should complete it’s current iteration before restarting. Defaults toFalsewhich will immediately cancel the currently running iteration and restart the routine with the new times provided.
- twitchio.ext.routines.routine(*, delta: datetime.timedelta | None = None, time: datetime.datetime | None = None, name: str | None = None, iterations: int | None = None, wait_first: bool = False, wait_remainder: bool = False, max_attempts: int | None = 5, stop_on_error: bool = False) Callable[[Callable[[...], Coroutine[Any, Any, Any]]], Routine]¶
This function is a decorator.
A decorator to assign a coroutine as a
Routine.Important
One parameter of either
timeordeltamust be passed. Both parameters CAN NOT be used together.- Parameters
delta (
datetime.timedelta| None) – Adatetime.timedeltaof time to wait per iteration of theRoutine. If this isNone, you must pass thetimeparameter. Defaults toNone.time (
datetime.datetime| None) – Adatetime.datetimeto schedule an run each iteration of theRoutine. TheRoutinewill run at the same time everyday. If this isNone, you must pass thedeltaparameter. Defaults toNone.name (str | None) – An optional name to use for this routine. Defaults to
Nonewhich uses the repr of theRoutine.iterations (int | None) – An optional
intamount of iterations to run this routine for. For example if set to3, theRoutinewill only run3times and complete. If set toNonethe routine will continue running until stopped or canceled. Defaults toNone.wait_first (bool) – Whether the
Routineshould wait the amount of time specified intimeordeltabefore starting. Defaults toFalse, which will run the first iteration immediately afterstart()is called.wait_remainder (bool) – Whether to wait only the remaining time to the next iteration after the current iteration completes. For example if your
Routineis scheduled to run every minute, and your iteration took30 seconds, the routine will only wait an additional30 secondsbefore running its next iteration. Defaults toFalsewhich means that theRoutinewill wait the full time after each iteration. Note: this has no effect when thetimeparameter is passed.max_attempts (int | None) – The maximum times the
Routineshould be allowed to error consecuitevely before stopping. When an error occurs and this parameter is set, the routine will sleep for a small backoff interval before retrying the iteration. If themax_attemptscounter is hit after multiple consecutive errors, the routine will stop. This counter resets when a successful iteration occurs. Note:max_attemptshas no effect whenstop_on_erroris set. If set toNone, the routine will backoff indefinitely. Defaults to5.stop_on_error (bool) – A bool indicating whether the
Routineshould immediately stop when encountering an error. This parameter takes precedence overmax_attempts. Defaults toFalse.
- Raises
TypeError – The function decorated is not a coroutine function.
RuntimeError – The
timeanddeltaarguments were both passed together. Only one of these parameters can be used.RuntimeError – Both the
timeanddeltaarguments are missing. One of these parameters must be used.
TwitchIO - Documentation