Skip to content

Commit

Permalink
Add support for <timer handle>.when()
Browse files Browse the repository at this point in the history
  • Loading branch information
Jens Jorgensen authored and elprans committed Aug 10, 2021
1 parent 20febe0 commit 62b2af9
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 0 deletions.
9 changes: 9 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,15 @@ async def main():
self.assertEqual(OK, 5)
self.assertEqual(NOT_OK, 0)

def test_loop_call_later_handle_when(self):
cb = lambda: False # NoQA
delay = 1.0
loop_t = self.loop.time()
handle = self.loop.call_later(delay, cb)
self.assertAlmostEqual(handle.when(), loop_t + delay, places=2)
handle.cancel()
self.assertTrue(handle.cancelled())


class TestBaseAIO(_TestBase, AIOTestCase):
pass
Expand Down
3 changes: 3 additions & 0 deletions uvloop/cbhandles.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ cdef class TimerHandle:
def cancel(self):
self._cancel()

def when(self):
return self.timer.get_when() * 1e-3


cdef format_callback_name(func):
if hasattr(func, '__qualname__'):
Expand Down
2 changes: 2 additions & 0 deletions uvloop/handles/timer.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ cdef class UVTimer(UVHandle):
object ctx
bint running
uint64_t timeout
uint64_t start_t

cdef _init(self, Loop loop, method_t callback, object ctx,
uint64_t timeout)

cdef stop(self)
cdef start(self)
cdef get_when(self)

@staticmethod
cdef UVTimer new(Loop loop, method_t callback, object ctx,
Expand Down
5 changes: 5 additions & 0 deletions uvloop/handles/timer.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ cdef class UVTimer(UVHandle):
self.ctx = ctx
self.running = 0
self.timeout = timeout
self.start_t = 0

cdef stop(self):
cdef int err
Expand All @@ -47,6 +48,7 @@ cdef class UVTimer(UVHandle):
if self.running == 0:
# Update libuv internal time.
uv.uv_update_time(self._loop.uvloop) # void
self.start_t = uv.uv_now(self._loop.uvloop)

err = uv.uv_timer_start(<uv.uv_timer_t*>self._handle,
__uvtimer_callback,
Expand All @@ -57,6 +59,9 @@ cdef class UVTimer(UVHandle):
return
self.running = 1

cdef get_when(self):
return self.start_t + self.timeout

@staticmethod
cdef UVTimer new(Loop loop, method_t callback, object ctx,
uint64_t timeout):
Expand Down

0 comments on commit 62b2af9

Please sign in to comment.