Class: Clock

Inherits:
Object
  • Object
show all
Defined in:
lib/fantasy/clock.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Clock

Returns a new instance of Clock.



7
8
9
10
11
12
13
# File 'lib/fantasy/clock.rb', line 7

def initialize(&block)
  @block = block
  @thread = nil
  @persistent = false # if persistent, clock is not stopped when loading new scene

  Global.clocks << self
end

Instance Attribute Details

#persistentObject

Returns the value of attribute persistent.



4
5
6
# File 'lib/fantasy/clock.rb', line 4

def persistent
  @persistent
end

#threadObject (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

Returns:

  • (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_nowObject



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

Returns:

  • (Boolean)


48
49
50
# File 'lib/fantasy/clock.rb', line 48

def started?
  !@thread.nil?
end

#stopObject



44
45
46
# File 'lib/fantasy/clock.rb', line 44

def stop
  Thread.kill(@thread) unless @thread.nil?
end