lib/clockwork.rb in clockwork-0.2.4 vs lib/clockwork.rb in clockwork-0.3.0

- old
+ new

@@ -1,8 +1,10 @@ module Clockwork class FailedToParse < StandardError; end; + @@events = [] + class Event attr_accessor :job, :last def initialize(period, job, block, options={}) @period = period @@ -16,11 +18,11 @@ @job end def time?(t) ellapsed_ready = (@last.nil? or (t - @last).to_i >= @period) - time_ready = (@at.nil? or (t.hour == @at[0] and t.min == @at[1])) + time_ready = (@at.nil? or ((@at[0].nil? or t.hour == @at[0]) and t.min == @at[1])) ellapsed_ready and time_ready end def run(t) @last = t @@ -44,14 +46,20 @@ msg.join("\n") end def parse_at(at) return unless at - m = at.match(/^(\d\d):(\d\d)$/) + m = at.match(/^(\d\d|\*+):(\d\d)$/) raise FailedToParse, at unless m - hour, min = m[1].to_i, m[2].to_i - raise FailedToParse, at if hour >= 24 or min >= 60 + if m[1][0] == '*' + hour = nil + else + hour = m[1].to_i + raise FailedToParse, at if hour >= 24 + end + min = m[2].to_i + raise FailedToParse, at if min >= 60 [ hour, min ] end end extend self @@ -66,14 +74,19 @@ raise NoHandlerDefined unless (defined?(@@handler) and @@handler) @@handler end def every(period, job, options={}, &block) - event = Event.new(period, job, block || get_handler, options) - @@events ||= [] - @@events << event - event + 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 + else + register(period, job, block, options) + end end def run log "Starting clock for #{@@events.size} events: [ " + @@events.map { |e| e.to_s }.join(' ') + " ]" loop do @@ -101,10 +114,17 @@ def clear! @@events = [] @@handler = nil end + + private + def register(period, job, block, options) + event = Event.new(period, job, block || get_handler, options) + @@events << event + event + end end unless 1.respond_to?(:seconds) class Numeric @@ -118,6 +138,6 @@ alias :hour :hours def days; self * 86400; end alias :day :days end -end \ No newline at end of file +end