Defining Rails application cron jobs in a rake task

posted by Ayush Newatia
10 February, 2021



rake has a variety of uses in Rails applications. You can use them to define and run installation and setup scripts, deployment scripts and pretty much anything you’d want to execute from the command line.

In Chapter24, I use a rake task that calls a Cloud66 HTTP endpoint to trigger a deploy.

namespace :chapter24 do
  task :deploy do
    key = Rails.application.credentials.cloud66[:deploy]
    exec "curl -X POST https://hooks.cloud66.com/stacks/redeploy/#{key} && echo \n"
  end
end

Additionally, I find they’re also brilliant for defining cron jobs for your application. Instead of invoking rails runner directly in your crontab, I think it’s far cleaner to define a rake task with the code you want to execute and invoke that in your crontab. That way the tasks are version controlled as well.

There’s a small catch. In Rails, rake tasks live in lib/tasks which means that they’re independent from your app code. But, as you would expect, Rails has a clean and elegant solution for this:

namespace :chapter24 do
  task :delete_unverified_comments => :environment do
    Comment::DeleteUnverifiedCommentsJob.perform_later
  end
end

The => :environment is all the magic you need to get access to your app code in the rake task. This task can then be invoked in your crontab as:

bundle exec rake chapter24:delete_unverified_comments

Doesn’t that look much cleaner than writing: 

bundle exec rails runner -e production "Comment::DeleteUnverifiedCommentsJob.perform_later"

in your crontab?

Rails ❤️