lib/clockwork/manager.rb in clockwork-0.6.0 vs lib/clockwork/manager.rb in clockwork-0.6.1
- old
+ new
@@ -4,10 +4,11 @@
attr_reader :config
def initialize
@events = []
+ @callbacks = {}
@config = default_configuration
@handler = nil
end
def thread_available?
@@ -29,40 +30,51 @@
def get_handler
raise NoHandlerDefined unless (defined?(@handler) and @handler)
@handler
end
+ def on(event, options={}, &block)
+ raise "Unsupported callback #{event}" unless [:before_tick, :after_tick, :before_run, :after_run].include?(event.to_sym)
+ (@callbacks[event.to_sym]||=[]) << block
+ end
+
def every(period, job, options={}, &block)
if options[:at].respond_to?(:each)
- each_options = options.clone
- options[:at].each do |at|
- each_options[:at] = at
- register(period, job, block, each_options)
- end
+ every_with_multiple_times(period, job, options, &block)
else
register(period, job, block, options)
end
end
+ def fire_callbacks(event, *args)
+ @callbacks[event].nil? || @callbacks[event].all? { |h| h.call(*args) }
+ end
+
def run
log "Starting clock for #{@events.size} events: [ " + @events.map { |e| e.to_s }.join(' ') + " ]"
loop do
tick
sleep(config[:sleep_timeout])
end
end
def tick(t=Time.now)
- to_run = @events.select do |event|
- event.time?(t)
- end
+ if (fire_callbacks(:before_tick))
+ to_run = @events.select do |event|
+ event.time?(t)
+ end
- to_run.each do |event|
- log "Triggering '#{event}'"
- event.run(t)
+ to_run.each do |event|
+ if (fire_callbacks(:before_run, event, t))
+ log "Triggering '#{event}'"
+ event.run(t)
+ fire_callbacks(:after_run, event, t)
+ end
+ end
end
+ fire_callbacks(:after_tick)
to_run
end
private
def log(msg)
@@ -84,8 +96,16 @@
options[:thread] = !!(options.has_key?(:thread) ? options[:thread] : config[:thread])
options[:tz] ||= config[:tz]
options
+ end
+
+ def every_with_multiple_times(period, job, options={}, &block)
+ each_options = options.clone
+ options[:at].each do |at|
+ each_options[:at] = at
+ register(period, job, block, each_options)
+ end
end
end
end