Class: Musa::Clock::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/musa-dsl/transport/timer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tick_period_in_seconds, correction: nil, stop: nil, delayed_ticks_error: nil, logger: nil, do_log: nil) ⇒ Timer

Returns a new instance of Timer.



6
7
8
9
10
11
12
13
14
# File 'lib/musa-dsl/transport/timer.rb', line 6

def initialize(tick_period_in_seconds, correction: nil, stop: nil, delayed_ticks_error: nil, logger: nil, do_log: nil)
  @period = tick_period_in_seconds.rationalize
  @correction = (correction || 0r).rationalize
  @stop = stop || false

  @delayed_ticks_error = delayed_ticks_error || 1.0
  @logger = logger
  @do_log = do_log
end

Instance Attribute Details

#periodObject

Returns the value of attribute period.



4
5
6
# File 'lib/musa-dsl/transport/timer.rb', line 4

def period
  @period
end

Instance Method Details

#continueObject



48
49
50
51
52
# File 'lib/musa-dsl/transport/timer.rb', line 48

def continue
  @stop = false
  @next_moment = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  @thread.run
end

#runObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/musa-dsl/transport/timer.rb', line 16

def run
  @thread = Thread.current

  @next_moment = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  loop do
    unless @stop
      yield

      @next_moment += @period
      to_sleep = (@next_moment + @correction) - Process.clock_gettime(Process::CLOCK_MONOTONIC)

      if @do_log && to_sleep.negative? & @logger
        tick_errors = -to_sleep / @period
        if tick_errors >= @delayed_ticks_error
          @logger.error "Timer delayed #{tick_errors.round(2)} ticks (#{-to_sleep.round(3)}s)"
        else
          @logger.warn "Timer delayed #{tick_errors.round(2)} ticks (#{-to_sleep.round(3)}s)"
        end
      end

      sleep to_sleep if to_sleep > 0.0
    end

    sleep if @stop
  end
end

#stopObject



44
45
46
# File 'lib/musa-dsl/transport/timer.rb', line 44

def stop
  @stop = true
end