Today I’d like to share a note on how to be confident that the new cron job is configured properly and is added to crontab.

I usually use whenever to configure cron jobs. Assuming that the deployment is set up properly, we will only need to check that the cron job is added to whenever’s schedule.rb file.

Here’s an example. Consider we want to clean up our database monthly on 1st of ‘Month’. It doesn’t matter what “clean up” means here. Let it be “delete old unpaid orders” or “delete draft posts made by anonymous users”

We’ve just wrote our task with test.

# cron.rb
class Cron
  def self.cleanup
    # ...
  end
end


# cron_spec.rb

describe Cron
  describe '.cleanup' do
    it "should delete unpaid orders created 1 month ago or older" do
      # ...
    end
  end
end

Let’s ensure we will run it at a right time, because we don’t need to run it often:

# cron_spec.rb

describe Cron

  let(:output) { `whenever -f` }

  describe '.cleanup' do
    it "should delete unpaid orders created 1 month ago or older" do
      # ...
    end

    it "should run monthly on 1st of Month at midnight" do
      cron_job = output.lines.find {|line| line.match 'Cron.cleanup'}
      cron_job.should start_with("0 0 1 * *")
    end
  end
end

Here we capture output of a part of crontab file generated by whenever, search for a line with our task and check that it configured properly. This test will fail if you don’t add a task to whenever config.

# config/schedule.rb

every 1.month, :at => 'midnight' do
  runner 'Cron.cleanup'
end

That’s it.