2010-01-04 04:43:58 +00:00
|
|
|
require 'singleton'
|
|
|
|
|
|
|
|
class Scheduler
|
|
|
|
include Singleton
|
|
|
|
|
|
|
|
WEEKLY = [ 7 ]
|
2010-01-05 00:43:15 +00:00
|
|
|
DAILY = [ 1 ]
|
2010-01-04 04:43:58 +00:00
|
|
|
|
2010-01-05 00:33:58 +00:00
|
|
|
def skip_to_dow(date, dow)
|
|
|
|
if dow.is_a? String
|
|
|
|
dow = Date::DAYNAMES.collect { |d| d.downcase }.index(dow.downcase)
|
|
|
|
end
|
|
|
|
|
|
|
|
if dow.is_a? Fixnum
|
|
|
|
while date.wday != dow
|
|
|
|
date += 1
|
|
|
|
end
|
|
|
|
end
|
|
|
|
date
|
|
|
|
end
|
|
|
|
|
2010-01-05 02:34:57 +00:00
|
|
|
def ok_to_add(date, index, prior, breaks)
|
2010-01-05 00:43:15 +00:00
|
|
|
ok = true
|
|
|
|
breaks.each do |i|
|
2010-01-05 02:34:57 +00:00
|
|
|
if i['from'] && i['to']
|
|
|
|
if (i['from'] <= date) && (i['to'] >= date)
|
|
|
|
ok = false
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
if i['at_index'] && i['for_days'] && prior
|
|
|
|
if i['at_index'] == index
|
|
|
|
ok = (date > (prior + i['for_days']))
|
|
|
|
end
|
2010-01-05 00:43:15 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
ok
|
|
|
|
end
|
|
|
|
|
2010-01-04 04:43:58 +00:00
|
|
|
def schedule(parameters, to_produce)
|
|
|
|
dates = []
|
|
|
|
|
2010-01-05 00:44:39 +00:00
|
|
|
if parameters['start']
|
|
|
|
current = parameters['start']
|
2010-01-05 02:34:57 +00:00
|
|
|
prior = nil
|
2010-01-04 04:43:58 +00:00
|
|
|
|
2010-01-05 00:44:39 +00:00
|
|
|
breaks = parameters['breaks'] || []
|
2010-01-05 00:43:15 +00:00
|
|
|
|
2010-01-05 02:34:57 +00:00
|
|
|
index = 0
|
2010-01-05 00:43:15 +00:00
|
|
|
while dates.length < to_produce
|
2010-01-05 00:44:39 +00:00
|
|
|
interval = parameters['interval'].shift
|
2010-01-04 04:43:58 +00:00
|
|
|
|
2010-01-05 03:00:34 +00:00
|
|
|
what_to_add = nil
|
|
|
|
|
|
|
|
if interval.is_a? String
|
|
|
|
current = skip_to_dow(current, interval)
|
|
|
|
|
|
|
|
what_to_add = 1
|
|
|
|
end
|
|
|
|
|
|
|
|
if ok_to_add(current, index, prior, breaks)
|
|
|
|
dates << current
|
|
|
|
prior = current
|
|
|
|
index += 1
|
2010-01-05 00:33:58 +00:00
|
|
|
end
|
2010-01-04 04:43:58 +00:00
|
|
|
|
2010-01-05 03:00:34 +00:00
|
|
|
if interval.is_a? Fixnum
|
|
|
|
what_to_add = interval
|
|
|
|
end
|
|
|
|
|
|
|
|
current += what_to_add
|
|
|
|
|
2010-01-05 00:44:39 +00:00
|
|
|
parameters['interval'] << interval
|
2010-01-04 04:43:58 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
dates
|
|
|
|
end
|
|
|
|
end
|