lib/clockwork.rb in clockwork-0.3.4 vs lib/clockwork.rb in clockwork-0.4.0
- old
+ new
@@ -1,5 +1,8 @@
+require 'logger'
+require 'tzinfo'
+
module Clockwork
@@events = []
class At
@@ -56,30 +59,46 @@
@period = period
@job = job
@at = At.parse(options[:at])
@last = nil
@block = block
+ if options[:if]
+ if options[:if].respond_to?(:call)
+ @if = options[:if]
+ else
+ raise ArgumentError.new(':if expects a callable object, but #{options[:if]} does not respond to call')
+ end
+ end
+
+ tz = options[:tz] || Clockwork.config[:tz]
+ @timezone = TZInfo::Timezone.get(tz) if tz
end
def to_s
@job
end
+ def convert_timezone(t)
+ @timezone ? @timezone.utc_to_local(t.dup.utc) : t
+ end
+
def time?(t)
- ellapsed_ready = (@last.nil? or (t - @last).to_i >= @period)
- ellapsed_ready and (@at.nil? or @at.ready?(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))
end
def run(t)
+ t = convert_timezone(t)
@last = t
@block.call(@job)
rescue => e
log_error(e)
end
def log_error(e)
- STDERR.puts exception_message(e)
+ Clockwork.config[:logger].error(e)
end
def exception_message(e)
msg = [ "Exception #{e.class} -> #{e.message}" ]
@@ -90,12 +109,26 @@
msg.join("\n")
end
end
+ def configure
+ yield(config)
+ end
+
+ def config
+ @@configuration
+ end
+
extend self
+ def default_configuration
+ { :sleep_timeout => 1, :logger => Logger.new(STDOUT) }
+ end
+
+ @@configuration = default_configuration
+
def handler(&block)
@@handler = block
end
class NoHandlerDefined < RuntimeError; end
@@ -119,33 +152,34 @@
def run
log "Starting clock for #{@@events.size} events: [ " + @@events.map { |e| e.to_s }.join(' ') + " ]"
loop do
tick
- sleep 1
+ sleep(config[:sleep_timeout])
end
end
def log(msg)
- puts msg
+ config[:logger].info(msg)
end
def tick(t=Time.now)
to_run = @@events.select do |event|
event.time?(t)
end
to_run.each do |event|
- log "Triggering #{event}"
+ log "Triggering '#{event}'"
event.run(t)
end
to_run
end
def clear!
@@events = []
@@handler = nil
+ @@configuration = Clockwork.default_configuration
end
private
def register(period, job, block, options)
event = Event.new(period, job, block || get_handler, options)