Skip to content

Commit

Permalink
Speed up calculating next run time of cron
Browse files Browse the repository at this point in the history
  • Loading branch information
nurse committed Dec 2, 2015
1 parent f7832c9 commit 5607f05
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 23 deletions.
27 changes: 6 additions & 21 deletions lib/perfectsched.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ module PerfectSched
require File.expand_path(v, File.dirname(__FILE__))
}

require 'cron-spec'
require 'chrono'
require 'tzinfo'

def self.open(config, &block)
Expand All @@ -71,28 +71,13 @@ def self.open(config, &block)
end

def self.cron_time(cron, timestamp, timezone)
begin
tab = CronSpec::CronSpecification.new(cron)
rescue
raise ArgumentError, "invalid cron format: #{$!}: #{cron.inspect}"
end

begin
tz = TZInfo::Timezone.get(timezone) if timezone
rescue
raise ArgumentError, "unknown timezone: #{$!}: #{timezone.inspect}"
unless /\A\s*(?:[0-9,*,\-\/]+\s+){4}[0-9,*,\-\/]+\z/ =~ cron
raise ArgumentError, "invalid cron format: #{cron.inspect}"
end

ts = (timestamp + 59) / 60 * 60
while true
t = Time.at(ts).utc
t = tz.utc_to_local(t) if tz
if tab.is_specification_in_effect?(t)
return ts
end
ts += 60
# FIXME break
end
ts = timestamp - 1 # compatibility
t = Time.find_zone!(timezone || 'UTC'.freeze).at(ts)
Chrono::NextTime.new(now: t, source: cron).to_time.to_i
end

def self.next_time(cron, before_timestamp, timezone)
Expand Down
2 changes: 1 addition & 1 deletion perfectsched.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Gem::Specification.new do |gem|
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.require_paths = ['lib']

gem.add_dependency "cron-spec", [">= 0.1.2", "<= 0.1.2"]
gem.add_dependency "chrono", "~> 0.1.0"
gem.add_dependency "sequel", "~> 3.48.0"
gem.add_dependency "tzinfo", "~> 1.1"
gem.add_dependency "perfectqueue", "~> 0.8.41"
Expand Down
2 changes: 1 addition & 1 deletion spec/perfect_sched_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
ts = PerfectSched.next_time('0 * * * *', 0, nil)
expect(ts).not_to be_nil
end
xit 'calculates 4 years quickly' do
it 'calculates 4 years quickly' do
t = Time.utc(2012,2,29)
ts = PerfectSched.next_time('0 0 29 2 *', t.to_i, nil)
expect(ts).to eq(Time.utc(2016,2,29).to_i)
Expand Down

0 comments on commit 5607f05

Please sign in to comment.