class SpiderFramework::Scheduler
通用调度器
调度器接受具有 call 或 start 方法的对象,并按照先入先出的顺序执行。
Public Class Methods
new()
click to toggle source
# File lib/scheduler.rb, line 6 def initialize @tasks = [] @item_handlers = {} end
Public Instance Methods
add_item(type, item, &block)
click to toggle source
# File lib/scheduler.rb, line 32 def add_item(type, item, &block) handler = @item_handlers[type.to_s.to_sym] raise "No handler found for type #{type.inspect}" unless handler raise NoMethodError, "undefined method `call' or `handle' for #{handler}" \ unless handler.respond_to?(:handle) || handler.respond_to?(:call) method = handler.respond_to?(:handle) ? :handle : :call p = proc do block ? handler.send(method, item, &block) : handler.send(method, item) end push(p) end
add_item_handler(type, handler)
click to toggle source
# File lib/scheduler.rb, line 47 def add_item_handler(type, handler) type = type.to_s.to_sym raise 'Handler already set' if @item_handlers.key?(type) @item_handlers[type] = handler end
loop()
click to toggle source
# File lib/scheduler.rb, line 11 def loop until @tasks.empty? task = @tasks.shift # Ruby queue performance: O(1) callable, block = [task[:callable], task[:block]] method = callable.respond_to?(:start) ? :start : :call block ? callable.send(method, &block) : callable.send(method) # 不执行任何逻辑了 end end
push(callable, &block)
click to toggle source
# File lib/scheduler.rb, line 23 def push(callable, &block) raise NoMethodError, "undefined method `call' or `start' for #{callable}" \ unless callable.respond_to?(:call) || callable.respond_to?(:start) @tasks.push(callable: callable, block: block) end
Also aliased as: <<