Skip to content

Commit 709a199

Browse files
committed
Add Routine.change_interval
1 parent 064d927 commit 709a199

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

twitchio/ext/routines/__init__.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,53 @@ def next_iteration(self) -> float:
451451
else:
452452
return max((self._last_start - datetime.datetime.now(tz=datetime.UTC)).total_seconds() + self._delta, 0)
453453

454+
def change_interval(
455+
self,
456+
*,
457+
delta: datetime.timedelta | None = None,
458+
time: datetime.datetime | None = None,
459+
wait_first: bool = False,
460+
) -> None:
461+
"""Method to change the running interval of a currently running routine.
462+
463+
Parameters
464+
----------
465+
delta: datetime.timedelta | None
466+
A :class:`datetime.timedelta` of time to wait per iteration of the :class:`~Routine`. If this is ``None``,
467+
you must pass the ``time`` parameter. Defaults to ``None``.
468+
time: datetime.datetime | None
469+
A :class:`datetime.datetime` to schedule an run each iteration of the :class:`~Routine`. The :class:`~Routine` will
470+
run at the same time everyday. If this is ``None``, you must pass the ``delta`` parameter. Defaults to ``None``.
471+
wait_first: bool
472+
An optional :class:`bool` indicating whether the currently running routine should complete it's current iteration
473+
before restarting. Defaults to ``False`` which will immediately cancel the currently running iteration and restart
474+
the routine with the new times provided.
475+
"""
476+
if not time and not delta:
477+
raise RuntimeError('One of either the "time" or "delta" arguments must be passed.')
478+
479+
if time is not None and delta is not None:
480+
raise RuntimeError(
481+
'The "time" argument can not be used in conjunction with the "delta" argument. Only one should be set.'
482+
)
483+
484+
if not time:
485+
delta_ = delta
486+
else:
487+
delta_ = None
488+
489+
now = datetime.datetime.now(time.tzinfo)
490+
if time < now:
491+
time = datetime.datetime.combine(now.date(), time.time())
492+
if time < now:
493+
time = time + datetime.timedelta(days=1)
494+
495+
self._time = time
496+
self._original_delta = delta_
497+
self._delta = delta_.total_seconds() if delta_ else None
498+
499+
self.restart(force=not wait_first)
500+
454501

455502
def routine(
456503
*,

0 commit comments

Comments
 (0)