Automation With Rails script/runner

Jan 31, 2007

There are going to be times as a Rails developer that you’ll need to automate tasks that need to be run on a periodic basis. In my instance I needed to automate sending out emails to users whose accounts were expiring soon. For those of you with a Unix background the first instinct is probably to use a cron job, which is correct. The issue is how to get to the scheduled cron job to interact with your Rails application. The solution? Rails script/runner command.

script/runner and Models

Script/runner isn’t talked about much, and I wouldn’t be surprised if many people just aren’t aware of it. The most common way I’ve found it used is to call methods from within Models. This is also a good way to keep this automation hidden from the public facing actions of your application.

Here’s a basic example:

class User < ActiveRecord::Base

def self.my_automated_task
  find(:all).each do |user|
    #do some stuff to each user here
  end
end

Then you would call this method by using this command set up as a cron job:

RAILS_ENV=production ./script/runner User.my_automated_task 

This is just skimming the surface of what can be done with script/runner, but it’s go place to start in getting familiar with automation in Rails.