lib/clockwork/event.rb in clockwork-0.7.0 vs lib/clockwork/event.rb in clockwork-0.7.1
- old
+ new
@@ -1,78 +1,67 @@
module Clockwork
class Event
attr_accessor :job, :last
def initialize(manager, period, job, block, options={})
+ validate_if_option(options[:if])
@manager = manager
@period = period
@job = job
@at = At.parse(options[:at])
@last = nil
@block = block
@if = options[:if]
- @thread = options[:thread]
- @timezone = options[:tz]
+ @thread = options.fetch(:thread, @manager.config[:thread])
+ @timezone = options.fetch(:tz, @manager.config[:tz])
end
- def to_s
- @job
- end
-
def convert_timezone(t)
@timezone ? t.in_time_zone(@timezone) : t
end
- def time?(t)
+ def run_now?(t)
t = convert_timezone(t)
- elapsed_ready = (@last.nil? or (t - @last).to_i >= @period)
- elapsed_ready and (@at.nil? or @at.ready?(t)) and (@if.nil? or @if.call(t))
+ elapsed_ready(t) and (@at.nil? or @at.ready?(t)) and (@if.nil? or @if.call(t))
end
def thread?
@thread
end
def run(t)
- t = convert_timezone(t)
- @last = t
-
+ @manager.log "Triggering '#{self}'"
+ @last = convert_timezone(t)
if thread?
if @manager.thread_available?
Thread.new { execute }
else
- log_error "Threads exhausted; skipping #{self}"
+ @manager.log_error "Threads exhausted; skipping #{self}"
end
else
execute
end
end
+ def to_s
+ job.to_s
+ end
+
+ private
def execute
@block.call(@job, @last)
rescue => e
- log_error e
- handle_error e
+ @manager.log_error e
+ @manager.handle_error e
end
- def log_error(e)
- @manager.config[:logger].error(e)
+ def elapsed_ready(t)
+ @last.nil? || (t - @last).to_i >= @period
end
- def exception_message(e)
- msg = [ "Exception #{e.class} -> #{e.message}" ]
-
- base = File.expand_path(Dir.pwd) + '/'
- e.backtrace.each do |t|
- msg << " #{File.expand_path(t).gsub(/#{base}/, '')}"
- end
-
- msg.join("\n")
- end
-
- def handle_error(e)
- if handler = @manager.get_error_handler
- handler.call(e)
+ def validate_if_option(if_option)
+ if if_option && !if_option.respond_to?(:call)
+ raise ArgumentError.new(':if expects a callable object, but #{if_option} does not respond to call')
end
end
end
end