Skip to content

Instantly share code, notes, and snippets.

@sdsykes
Created April 11, 2011 07:53
Show Gist options
  • Save sdsykes/913210 to your computer and use it in GitHub Desktop.
Save sdsykes/913210 to your computer and use it in GitHub Desktop.
background jobs
Here's what I do:
This is Rails 2
pid = fork do
%x{RAILS_ENV=#{Rails.env} #{RAILS_ROOT + "/script/runner"} '#{script}'}
exit!
end
Process.detach pid
For Rails 3 you need to do this:
pid = fork do
%x{RAILS_ENV=#{Rails.env} rails runner '#{script}'}
exit!
end
Process.detach pid
So we fork, then run a system script that runs up rails in a new process. The forked
process will wait for the rails runner process to finish, so we just detach from that
and forget it.
Your rails environment is there in the runner environment, so the way I do things is to
write the Job I need to do to the database first, then make my script read it.
So I have a class called Job, and I write some job details to the jobs table.
When the process is started it reads those details and runs whatever image processing you
need then writes a done timestamp to the table. Which is what this command does:
Job.find_by_id(#{id}).run
So the whole action looks something like this:
job = Job.create(:filename=>"image_file_whatever", :parameters=>"something")
script = "Job.find_by_id(#{job.id}).run"
pid = fork do
%x{RAILS_ENV=#{Rails.env} rails runner '#{script}'}
exit!
end
Process.detach pid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment