Class: Iyyov::Scheduler

Inherits:
Object
  • Object
show all
Defined in:
lib/iyyov/scheduler.rb

Overview

Maintains a queue of Task to be executed at fixed or periodic times.

Defined Under Namespace

Classes: TimeComp

Instance Method Summary collapse

Constructor Details

#initializeScheduler

Returns a new instance of Scheduler.



28
29
30
31
32
33
34
# File 'lib/iyyov/scheduler.rb', line 28

def initialize
  # min heap
  @queue = Java::java.util.PriorityQueue.new( 67, TimeComp.new )
  @lock = Mutex.new
  @shutdown_handler = nil
  @log = RJack::SLF4J[ self.class ]
end

Instance Method Details

#add(t, now = Time.now) ⇒ Object



36
37
38
# File 'lib/iyyov/scheduler.rb', line 36

def add( t, now = Time.now )
  @queue.add( t ) if t.schedule( now )
end

#event_loopObject

Loop forever executing tasks or waiting for the next to be ready. Return only when the queue is empty (which may be arranged by on_exit) or if a Task returns :shutdown.



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/iyyov/scheduler.rb', line 77

def event_loop
  rc = nil

  # While not shutdown
  while ( rc != :shutdown )
    now = Time.now
    delta = 0.0

    @lock.synchronize do
      # While we don't need to wait, and a task is available
      while ( delta <= 0.0 && ( task = peek ) && rc != :shutdown )
        delta = task.next_time - now

        if delta <= 0.0
          task = poll

          rc = task.run
          add( task, now ) unless ( rc == :shutdown || rc == :stop )
        end
      end
    end #lock

    break unless delta > 0.0
    sleep delta
  end

  if rc == :shutdown
    @log.debug "Begin scheduler shutdown sequence."
    @queue.clear
    off_exit
  end
  rc
end

#off_exitObject

Deregister any previously added on_exit block



66
67
68
69
70
71
72
# File 'lib/iyyov/scheduler.rb', line 66

def off_exit
  if @shutdown_handler
    @log.debug { "Unregistered exit: #{ @shutdown_handler.handler }" }
    @shutdown_handler.unregister
    @shutdown_handler = nil
  end
end

#on_exit(&block) ⇒ Object

Execute the specified block on exit (in a shutdown thread.) The Scheduler queue is drained such that the on_exit block is guaranteed to be the last to run.



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/iyyov/scheduler.rb', line 51

def on_exit( &block )
  off_exit
  @shutdown_handler = ShutdownHandler.new do

    # Need to lock out the event loop since exit handler is called
    # from a different thread.
    @lock.synchronize do
      @queue.clear
      block.call
    end
  end
  @log.debug { "Registered exit: #{ @shutdown_handler.handler }" }
end

#peekObject



40
41
42
# File 'lib/iyyov/scheduler.rb', line 40

def peek
  @queue.peek
end

#pollObject



44
45
46
# File 'lib/iyyov/scheduler.rb', line 44

def poll
  @queue.poll
end