Created
April 11, 2011 07:53
-
-
Save sdsykes/913210 to your computer and use it in GitHub Desktop.
background jobs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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