Some notes on cron, whenever and rake
I recently had to set up some cron jobs from an app that I was writing. I learned a couple of things so I thought I’d put them here. I’ve covered setting up precisely fortnightly cron jobs, setting up the whenever gem and how I tackled some of the errors that I came up against while trying to set it up.
Fortnightly Jobs
Setting up precisely fortnightly jobs that need to run on every other monday is quite easy. You don’t have to settle for just running the jobs on the 1st and the 15th. Set your job to run onw whichever day of the week that you want it to and set it to run every week. Include this in the actual command to be run:
expr `date +\%W` \% 2 > /dev/null || fortnightly_script.sh
Whenever
Whenever( github link ) is a nifty gem that you can use to modify your crontab easily from your application using some sort of capistrano recipie of rake task. First off install the gem with
$ gem install whenever
$ wheneverize # Excute this inside your app to setup the necessary files
Now edit the schedule.rb file where you can easily define your jobs in plain ruby. Now you can run the binary whenever —update-crontab to update your crontab cleanly from your capistrano recipies. When I tried to run the command however I ran into some difficulties. Read on …
Error: Rakefile: undefined method `import’ for main:Object (NoMethodError)
I ran into this error while trying to use the whenever gem in my app. Whenever I tried to run the whenever command I got this error:
./Rakefile:3: undefined method `import' for main:Object (NoMethodError)
from /opt/ruby-enterprise-1.8.7-2009.10/lib/ruby/gems/1.8/gems/whenever-0.4.1/lib/whenever.rb:5:in `load'
from /opt/ruby-enterprise-1.8.7-2009.10/lib/ruby/gems/1.8/gems/whenever-0.4.1/lib/whenever.rb:5
from /opt/ruby-enterprise-1.8.7-2009.10/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /opt/ruby-enterprise-1.8.7-2009.10/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from /opt/ruby-enterprise-1.8.7-2009.10/lib/ruby/gems/1.8/gems/whenever-0.4.1/bin/whenever:7
from /opt/ruby-enterprise-1.8.7-2009.10/bin/whenever:19:in `load'
from /opt/ruby-enterprise-1.8.7-2009.10/bin/whenever:19'''''
I fixed this by adding
require 'rake'
at the beginning of my Rakefile. I’m still not sure what exactly the problem was and how that line solved it. Maybe some of you more knowledgeable netizens could clear it up.