Class: Clock
- Inherits:
-
Object
- Object
- Clock
- Defined in:
- lib/fantasy/clock.rb
Instance Attribute Summary collapse
-
#persistent ⇒ Object
Returns the value of attribute persistent.
-
#thread ⇒ Object
readonly
Returns the value of attribute thread.
Instance Method Summary collapse
-
#initialize(&block) ⇒ Clock
constructor
A new instance of Clock.
- #persistent? ⇒ Boolean
- #repeat(seconds: 1, times: Float::INFINITY) ⇒ Object
- #run_now ⇒ Object
- #run_on(seconds:) ⇒ Object
- #started? ⇒ Boolean
- #stop ⇒ Object
Constructor Details
Instance Attribute Details
#persistent ⇒ Object
Returns the value of attribute persistent.
4 5 6 |
# File 'lib/fantasy/clock.rb', line 4 def persistent @persistent end |
#thread ⇒ Object (readonly)
Returns the value of attribute thread.
5 6 7 |
# File 'lib/fantasy/clock.rb', line 5 def thread @thread end |
Instance Method Details
#persistent? ⇒ Boolean
52 53 54 |
# File 'lib/fantasy/clock.rb', line 52 def persistent? @persistent end |
#repeat(seconds: 1, times: Float::INFINITY) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/fantasy/clock.rb', line 30 def repeat(seconds: 1, times: Float::INFINITY) times_executed = 0 @thread = Thread.new do while times_executed < times @block.call times_executed += 1 seconds_to_sleep = seconds.is_a?(Range) ? rand(seconds) : seconds sleep(seconds_to_sleep) end end end |
#run_now ⇒ Object
15 16 17 18 19 20 |
# File 'lib/fantasy/clock.rb', line 15 def run_now @thread = Thread.new do @block.call end end |
#run_on(seconds:) ⇒ Object
22 23 24 25 26 27 28 |
# File 'lib/fantasy/clock.rb', line 22 def run_on(seconds:) @thread = Thread.new do sleep(seconds) @block.call end end |
#started? ⇒ Boolean
48 49 50 |
# File 'lib/fantasy/clock.rb', line 48 def started? !@thread.nil? end |
#stop ⇒ Object
44 45 46 |
# File 'lib/fantasy/clock.rb', line 44 def stop Thread.kill(@thread) unless @thread.nil? end |