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



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
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/nestene/actor/delayed_scheduler.rb', line 39

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 = now + 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?
    if now >= @schedule.first[1].execute_at
      async.schedule_methods
    else
      to_wait = @schedule.first[1].execute_at - now
      @timer = after(to_wait){async.schedule_methods}
    end
  end

end

#schedule_structObject



16
17
18
# File 'lib/nestene/actor/delayed_scheduler.rb', line 16

def schedule_struct
  @schedule.to_structure
end

#update_schedule(topic, auton_id, state) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/nestene/actor/delayed_scheduler.rb', line 21

def update_schedule topic, auton_id, state

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

  if state

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

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

    async.schedule_methods
  end

end