Skip to content

Instantly share code, notes, and snippets.

@lucas-clemente
Last active August 29, 2015 14:02
Show Gist options
  • Save lucas-clemente/3d5cc559728fe35ff955 to your computer and use it in GitHub Desktop.
Save lucas-clemente/3d5cc559728fe35ff955 to your computer and use it in GitHub Desktop.
Proof of concept for calculating cron job times
#!/usr/bin/env ruby
# Calculate the next match for cron conditions (secs).
# Numbers > 60 mean the match is in the next minute.
#
# Arbitrary conditions:
# just take the minimum of all the individual ones.
# 60 secs / min
MAX = 60
# Next match for a range
def next_range(current, range)
case
when current < range.first
range.first
when current > range.last
60 + range.first
when current > range.first && current < range.last
current + 1
else
raise "unexpected"
end
end
# Next match for a modulo condition
def next_mod(current, operand)
((current / operand).floor + 1) * operand
end
# Next match for an exact condition
def next_exact(current, exact)
if current < exact
exact
else
60 + exact
end
end
require "minitest/autorun"
class CronTest < MiniTest::Test
def test_range
assert_equal 20, next_range(10, 20..30)
assert_equal 80, next_range(50, 20..30)
assert_equal 25, next_range(24, 20..30)
end
def test_mod
assert_equal 10, next_mod(0, 10)
assert_equal 10, next_mod(5, 10)
assert_equal 60, next_mod(59, 10)
end
def test_exact
assert_equal 10, next_exact(0, 10)
assert_equal 70, next_exact(11, 10)
end
end
@sharpner
Copy link

nice! I can't think of anything that won't work right now - Mind if I share it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment