duck_punching

Ruby, Rails and tech. No ducks were harmed in the making of this blog.

Archive for December, 2008

Timely assistance with cron intervals using Cronos

For anyone who has used cron before I am sure there have been occasions where you have buggered it up and run the task too few or too many times or at the completely wrong time. I know I have. Its not the cron is terribly hard its just sometimes is not the best mental map for specifying a repeating interval.

Well as a fun summer project I thought I would create a Ruby DSL for cron to generate the intervals using a more natural syntax to help avoid mistakes. The result is Cronos. Its influenced by the Active Support time helpers so you can chain together English like commands that you would likely use when describing a repeating interval.

Some examples from the readme:

cron = Cronos::Interval
cron.new.hourly.to_s
# => '0 * * * *'
cron.new.daily.to_s
# => '0 0 * * *'
cron.new.weekly.to_s
# => '0 0 * * 0'
cron.new.weekdays.at(12.30).to_s
# => '30 12 * * 1-5'
cron.new.weekends.at(12.30).to_s
# => '30 12 * * 0,6'
cron.new.at('1.30pm').daily.to_s
# => '30 13 * * *'
cron.new.every(6).hours.on('15th').of(:january).to_s
# => '0 0,6,12,18 15 1 *'
cron.new.every(20).minutes.on(15..18).of(:jan, :feb, :mar).to_s
# => '0,20,40 * 15-18 1,2,3 *'
cron.new.at(14.45).on_days(:monday, :tuesday).to_s
# => '45 14 * * 1,2'

It would be great to see Cronos integrated it into other cron tools for Ruby as to extend them with DSL to generate just the interval part. The CronEdit project is one that might find it a useful addition.

Its a first crack and its not magical at all so you can easily jump in and fiddle and perhaps improve it. The code is up on GitHub (where else?!).

UPDATE:
Examples were confusing so clarified the output of each statement irb style.

No comments