You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

83 lines
2.2 KiB

  1. @cython.no_gc_clear
  2. cdef class UVTimer(UVHandle):
  3. cdef _init(self, Loop loop, method_t callback, object ctx,
  4. uint64_t timeout):
  5. cdef int err
  6. self._start_init(loop)
  7. self._handle = <uv.uv_handle_t*> PyMem_RawMalloc(sizeof(uv.uv_timer_t))
  8. if self._handle is NULL:
  9. self._abort_init()
  10. raise MemoryError()
  11. err = uv.uv_timer_init(self._loop.uvloop, <uv.uv_timer_t*>self._handle)
  12. if err < 0:
  13. self._abort_init()
  14. raise convert_error(err)
  15. self._finish_init()
  16. self.callback = callback
  17. self.ctx = ctx
  18. self.running = 0
  19. self.timeout = timeout
  20. cdef stop(self):
  21. cdef int err
  22. if not self._is_alive():
  23. self.running = 0
  24. return
  25. if self.running == 1:
  26. err = uv.uv_timer_stop(<uv.uv_timer_t*>self._handle)
  27. self.running = 0
  28. if err < 0:
  29. exc = convert_error(err)
  30. self._fatal_error(exc, True)
  31. return
  32. cdef start(self):
  33. cdef int err
  34. self._ensure_alive()
  35. if self.running == 0:
  36. # Update libuv internal time.
  37. uv.uv_update_time(self._loop.uvloop) # void
  38. err = uv.uv_timer_start(<uv.uv_timer_t*>self._handle,
  39. __uvtimer_callback,
  40. self.timeout, 0)
  41. if err < 0:
  42. exc = convert_error(err)
  43. self._fatal_error(exc, True)
  44. return
  45. self.running = 1
  46. @staticmethod
  47. cdef UVTimer new(Loop loop, method_t callback, object ctx,
  48. uint64_t timeout):
  49. cdef UVTimer handle
  50. handle = UVTimer.__new__(UVTimer)
  51. handle._init(loop, callback, ctx, timeout)
  52. return handle
  53. cdef void __uvtimer_callback(uv.uv_timer_t* handle) with gil:
  54. if __ensure_handle_data(<uv.uv_handle_t*>handle, "UVTimer callback") == 0:
  55. return
  56. cdef:
  57. UVTimer timer = <UVTimer> handle.data
  58. method_t cb = timer.callback
  59. timer.running = 0
  60. try:
  61. cb(timer.ctx)
  62. except BaseException as ex:
  63. timer._error(ex, False)