Skip to content

Commit 37dd0ed

Browse files
committed
Add routine argument wait_first which waits the specided hours, minutes or seconds before starting the first iteration.
1 parent 036d5f7 commit 37dd0ed

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

twitchio/ext/routines/__init__.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ def __init__(
6868
iterations: Optional[int] = None,
6969
time: Optional[datetime.datetime] = None,
7070
delta: Optional[float] = None,
71+
wait_first: Optional[bool] = False
7172
):
7273
self._coro = coro
7374
self._loop = loop or asyncio.get_event_loop()
@@ -90,6 +91,7 @@ def __init__(
9091

9192
self._stop_set = False
9293
self._restarting = False
94+
self._wait_first = wait_first
9395

9496
self._stop_on_error = True
9597

@@ -257,6 +259,9 @@ async def _routine(self, *args, **kwargs) -> None:
257259
wait = compute_timedelta(self._time)
258260
await asyncio.sleep(wait)
259261

262+
if self._wait_first and not self._time:
263+
await asyncio.sleep(self._delta)
264+
260265
while True:
261266
start = datetime.datetime.now(datetime.timezone.utc)
262267

@@ -285,8 +290,8 @@ async def _routine(self, *args, **kwargs) -> None:
285290
else:
286291
sleep = max((start - datetime.datetime.now(datetime.timezone.utc)).total_seconds() + self._delta, 0)
287292

288-
await asyncio.sleep(sleep)
289293
self._completed_loops += 1
294+
await asyncio.sleep(sleep)
290295

291296
try:
292297
if self._after:
@@ -304,6 +309,7 @@ def routine(
304309
hours: Optional[float] = 0,
305310
time: Optional[datetime.datetime] = None,
306311
iterations: Optional[int] = None,
312+
wait_first: Optional[bool] = False
307313
):
308314
"""A decorator to assign a coroutine as a :class:`Routine`.
309315
@@ -320,6 +326,9 @@ def routine(
320326
iterations: Optional[int]
321327
The amount of iterations to run this routine before stopping.
322328
If set to None or 0, the routine will run indefinitely.
329+
wait_first: Optional[bool]
330+
Whether to wait the specified time before running the first iteration.
331+
This has no effect when the time argument is used. Defaults to False.
323332
324333
Raises
325334
------
@@ -357,6 +366,6 @@ def decorator(coro: Callable) -> Routine:
357366
if not asyncio.iscoroutinefunction(coro):
358367
raise TypeError(f"Expected coroutine function not type, {type(coro).__name__!r}.")
359368

360-
return Routine(coro=coro, time=time_, delta=delta, iterations=iterations)
369+
return Routine(coro=coro, time=time_, delta=delta, iterations=iterations, wait_first=wait_first)
361370

362371
return decorator

0 commit comments

Comments
 (0)