timer.monkey2 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #If __TARGET__="emscripten"
  2. #Import "timer_emscripten"
  3. #Else
  4. Namespace std.timer
  5. Private
  6. Using std.time
  7. Using std.collections
  8. Using std.fiber
  9. Public
  10. #rem monkeydoc The Timer class.
  11. #end
  12. Class Timer
  13. #rem monkeydoc Creates a new Timer.
  14. Creates new timer with `hertz` frequency.
  15. The timer will continually invoke the `fired` function at the rate of `hertz` times per second.
  16. #end
  17. Method New( hertz:Double,fired:Void() )
  18. New Fiber( Lambda()
  19. Local period:=1/hertz
  20. Local timeout:=Now()+period
  21. While Not _cancelled
  22. Local now:=Now()
  23. Local sleep:=timeout-now
  24. If sleep>0
  25. Fiber.Sleep( sleep )
  26. Continue
  27. Endif
  28. If _cancelled Exit
  29. If Not _suspended fired()
  30. timeout+=period
  31. Wend
  32. End )
  33. End
  34. #rem monkeydoc Timer suspended state.
  35. #end
  36. Property Suspended:Bool()
  37. Return _suspended
  38. Setter( suspended:Bool )
  39. _suspended=suspended
  40. End
  41. #rem monkeydoc Cancels the timer.
  42. #end
  43. Method Cancel()
  44. _cancelled=True
  45. End
  46. Private
  47. Field _suspended:Bool
  48. Field _cancelled:Bool
  49. End
  50. #Endif