Guest User

Untitled

a guest
Aug 14th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1.  
  2. require 'monitor'
  3.  
  4. class Timer
  5. # include MonitorMixin
  6.  
  7. def self.repeat_every(interval_sec, &code)
  8. t = Timer.new(interval_sec, code)
  9. t.start
  10. t
  11. end
  12.  
  13. def initialize(interval, code)
  14. extend MonitorMixin
  15. @interval = interval
  16. @code = code
  17. end
  18.  
  19. def start
  20. synchronize do
  21. raise "Already running" if @thread
  22.  
  23. @stop = false
  24.  
  25. @thread = Thread.new do
  26. intv = synchronize { @interval }
  27.  
  28. until synchronize { @stop }
  29. t = Time.now
  30. @code.call
  31. sleep(t + intv - Time.now)
  32. end
  33.  
  34. synchronize { @thread = nil }
  35. end
  36. end
  37.  
  38. self
  39. end
  40.  
  41. def stop
  42. synchronize do
  43. @stop = true
  44. end
  45.  
  46. self
  47. end
  48.  
  49. def shutdown
  50. th = synchronize do
  51. @stop = true
  52. @thread
  53. end
  54.  
  55. th.join if th
  56.  
  57. self
  58. end
  59. end
  60.  
  61. t = Timer.repeat_every 1 do
  62. puts "foo"
  63. end
  64.  
  65. sleep 20
  66.  
  67. t.stop
Add Comment
Please, Sign In to add comment