Skip to content

Commit

Permalink
Use a coroutine that does nothing.
Browse files Browse the repository at this point in the history
  • Loading branch information
rodrigogiraoserrao committed Jun 9, 2023
1 parent 0c32c05 commit e3f9dc1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
4 changes: 1 addition & 3 deletions src/textual/_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ async def sleep(secs: float) -> None:
Args:
secs: Number of seconds to sleep for.
"""
sleep = win_sleep(secs)
if sleep is not None:
await asyncio.create_task(sleep)
await asyncio.create_task(win_sleep(secs))

else:

Expand Down
14 changes: 12 additions & 2 deletions src/textual/_win_sleep.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,25 @@ async def time_sleep_coro(secs: float):
print("Exception found")

def sleep(secs: float) -> Coroutine[None, None, None]:
"""Wrapper around `time.sleep` to match the signature of the main case below."""
return time_sleep_coro(secs)

else:

def sleep(secs: float) -> Coroutine[None, None, None] | None:
async def no_sleep_coro():
"""Creates a coroutine that does nothing for when no sleep is needed."""
pass

def sleep(secs: float) -> Coroutine[None, None, None]:
"""A replacement sleep for Windows.
Note that unlike `time.sleep` this *may* sleep for slightly less than the
specified time. This is generally not an issue for Textual's use case.
In order to create a timer that _can_ be cancelled on Windows, we need to
create a timer and a separate event, and then we wait for either of the two
things. When Textual wants to quit, we set the cancel event.
Args:
secs: Seconds to sleep for.
"""
Expand All @@ -51,7 +60,7 @@ def sleep(secs: float) -> Coroutine[None, None, None] | None:
sleep_for = max(0, secs - 0.001)
if sleep_for < 0.0005:
# Less than 0.5ms and its not worth doing the sleep
return None
return no_sleep_coro()

timer = kernel32.CreateWaitableTimerExW(
None,
Expand Down Expand Up @@ -79,6 +88,7 @@ def sleep(secs: float) -> Coroutine[None, None, None] | None:
return time_sleep_coro(sleep_for)

def cancel_inner():
"""Sets the cancel event so we know we can stop waiting for the timer."""
kernel32.SetEvent(cancel_event)

async def cancel():
Expand Down

0 comments on commit e3f9dc1

Please sign in to comment.