Thursday 3 September 2009

A rake task to install crons

Assuming the cron tasks you want to run are stored in script/crons/{daily,hourly,monthly,weekly}/... this rake task will create the necessary crons on the system
namespace :crons do
desc "Install the crons we need to run this site"
task :install do
text = ''

template = "@%s (cd %s ; /usr/local/bin/ruby script/runner -e production script/crons/%s/%s)\n"

Dir["#{RAILS_ROOT}/script/crons/*/*"].each do |file|
if file =~ /crons\/daily/
text << template % ['daily', RAILS_ROOT, 'daily', File.basename(file)]
elsif file =~ /crons\/hourly/
text << template % ['hourly', RAILS_ROOT, 'hourly', File.basename(file)]
elsif file =~ /crons\/monthly/
text << template % ['monthly', RAILS_ROOT, 'monthly', File.basename(file)]
elsif file =~ /crons\/weekly/
text << template % ['weekly', RAILS_ROOT, 'weekly', File.basename(file)]
else
puts "Unknown file #{file}"
end
end

cron_file = "#{RAILS_ROOT}/script/crons/crontab.txt"

if File.exist?(cron_file)
File.delete(cron_file)
end

unless text == ''
f = File.new(cron_file, "w")
f.puts text
f.close
end
end

desc "Remove any previously installed crons"
task :remove do
cron_file = "#{RAILS_ROOT}/script/crons/crontab.txt"

if File.exist?(cron_file)
File.delete(cron_file)
end
end
end

To run it just go rake crons:install and it will create the crontabs as a text file. Then we can use the capistrano task to set them up
namespace :deploy do
namespace :crons do
desc "Installing the crons"
task :install, :roles => :db do
run "(cd #{deploy_to}/current ; rake crons:install)"
run "cat #{deploy_to}/current/script/crons/crontab.txt | crontab -"
end
desc "Remove the crons"
task :remove, :roles => :db do
run "crontab -r"
run "(cd #{deploy_to}/current ; rake crons:remove)"
end
end
end

You could probably do it all in the rake task if you wanted. You might want to set up some hooks to run this after a deploy

No comments:

Post a Comment