Class: Yuuki::PeriodicCaller

Inherits:
Caller
  • Object
show all
Defined in:
lib/yuuki/periodic.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Caller

#add, #alive?, #ignore_tag_error, #join, require_dir, #run_method, #run_select, #run_tag, #runners, #tags

Constructor Details

#initialize(*instances, use_yoshinon: true) ⇒ PeriodicCaller

Returns a new instance of PeriodicCaller.



39
40
41
42
# File 'lib/yuuki/periodic.rb', line 39

def initialize(*instances, use_yoshinon: true)
  super
  @first_run = true
end

Instance Attribute Details

#current_timeFloat (readonly)

Returns the current value of current_time.

Returns:

  • (Float)

    the current value of current_time



36
37
38
# File 'lib/yuuki/periodic.rb', line 36

def current_time
  @current_time
end

#first_runBoolean (readonly)

Returns the current value of first_run.

Returns:

  • (Boolean)

    the current value of first_run



36
37
38
# File 'lib/yuuki/periodic.rb', line 36

def first_run
  @first_run
end

Instance Method Details

#on_error {|error| ... } ⇒ Object

sets error callback

Yields:

  • (error)

Yield Parameters:

  • error (Exception)


47
48
49
# File 'lib/yuuki/periodic.rb', line 47

def on_error(&block)
  @on_error = block
end

#run(gmtoff = Time.now.gmtoff, **args, &block) ⇒ Object

runs the periodic caller

Parameters:

  • gmtoff (Numeric) (defaults to: Time.now.gmtoff)

    GMT Offset

  • args (Object)

    arguments



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/yuuki/periodic.rb', line 54

def run(gmtoff = Time.now.gmtoff, **args, &block)
  last_time = nil
  loop do
    @current_time = Time.now.to_f
    begin
      select_proc = proc do |_method, meta|
        next true if @first_run && meta[:first_run]
        next false unless meta[:periodic]
        next false unless last_time

        c = @current_time + gmtoff
        l = last_time + gmtoff
        (l.div(meta[:periodic]) + 1) * meta[:periodic] <= c
      end
      run_select(select_proc, **args, &block)
    rescue StandardError
      @on_error ? @on_error[$!] : raise
    end
    @first_run = false

    last_time = @current_time
    ((@current_time + 1).floor - Time.now.to_f).tap {|e| sleep e if e > 0}
  end
end