Class: Nestene::Actor::DelayedScheduler

Inherits:
Object
  • Object
show all
Includes:
Celluloid, Celluloid::Notifications
Defined in:
lib/nestene/actor/delayed_scheduler.rb

Instance Method Summary collapse

Constructor Details

#initializeDelayedScheduler

Returns a new instance of DelayedScheduler.



10
11
12
13
14
# File 'lib/nestene/actor/delayed_scheduler.rb', line 10

def initialize
  subscribe('state_update', :update_schedule)
  @schedule = []
  @timer = nil
end

Instance Method Details

#schedule_methodsObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/nestene/actor/delayed_scheduler.rb', line 32

def schedule_methods

  if @timer
    @timer.cancel
  end

  now = Time.now

  loop do
    (auton_id, delayed_method) = @schedule.shift

    if auton_id
      execute_in = delayed_method.execute_at - now
      if execute_in <= 0
        Celluloid::Actor["storage:%s" % auton_id].update do |state|
          delayed = state.queue.delayed.shift
          execute_in = delayed.execute_at - now
          if execute_in <= 0
            method = ScheduledMethod.new(delayed)
            state.queue.to_execute << method
          end
          if delayed.every
            delayed.execute_at += delayed.every
            state.queue.add_delayed(delayed)
          end
        end
      else
        @schedule.unshift [auton_id, delayed_method]
        break
      end
    else
      break
    end
  end

  unless @schedule.empty?
    to_wait = @schedule.first[1].execute_at - now
    @timer = after(to_wait){async.schedule_methods}
  end

end

#update_schedule(topic, auton_id, state) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/nestene/actor/delayed_scheduler.rb', line 17

def update_schedule topic, auton_id, state

  @schedule.delete_if{|e| e.first == auton_id}

  state.queue.delayed.each do |d|
    @schedule << [auton_id, d]
  end

  @schedule.sort_by!{|e| e[1].execute_at}

  async.schedule_methods

end