Wednesday, July 31, 2013

Performing cron jobs in rails through clockwork

The Clockwork Gem allows us to run cron jobs in a ruby application. Since I was using this today, its documentation is a bit of a blocker. The github wiki gives the following example:
require 'clockwork'
include Clockwork

handler do |job|
  puts "Running #{job}"
end

every(10.seconds, 'frequent.job')
every(3.minutes, 'less.frequent.job')
every(1.hour, 'hourly.job')

every(1.day, 'midnight.job', :at => '00:00')
However, I needed to run custom tasks, which is not mentioned there. Here's how I did the necessary work
require_relative "../config/environment"
require_relative "../config/boot"
require 'clockwork'

include Clockwork

handler do |job|
 puts "running the scheduled job #{job}."
end

every(30.seconds, 'test job execution'){Module::Class.new.method_to_call}
I added the require_relative calls to environment.rb & boot.rb to load the rails framework from this clock.rb file, which is placed in lib folder. This example is calling a custom module placed in the lib folder in the same rails app.
As this application is to be deployed over heroku, we need to have 2 dynos, one for the rails and another for the extra task. We define this through Procfile file present at rails root with the following contents:
web    bundle exec unicorn -p $PORT -c ./config/unicorn.rb
clock  bundle exec clockwork app/lib/clock.rb
Which does the necessary things for me at heroku. To run long running tasks, you may want to use delayed jobs, but it will involve another dyno for management so I left it in this solution.

1 comment:

Unknown said...

Use command on terminal to start Clockworld (rails)

bundle exec clockwork lib/clock.rb