Running rake task in background and not blocking the port
In this screencast Ryan Bates explains how to execute a rake task in background on run time. This will make controller return the response to the user fast. In the meantime email will be sent through the background job.
In short this is the solution he proposes.
def call_rake
system "rake #{task} &"
end
It is a short and sweet solution when you do not want to roll out other background job processing tools. It works pretty well. However I discovered one issue with the solution.
While developing validation functionality in admin_data I needed to demand a background job on run time and I used the solution proposed above.
Let’s say that I start a rake task on background which lasts for 10 minutes. In the next 10 minutes if I kill my script/server ( I am in development mode) and if I try to start my server, I was getting following message.
Address already in use - bind(2) (Errno::EADDRINUSE)
It seems that when the rake job is pushed to background, it inherits all the properties of the parent process including the port number of the server. It means that as long as the child process is alive, the parent process’s port number is taken.
This solution fixes the problem.
command = "rake #{task} #{args.join(' ')}"
p1 = Process.fork { system(command) }
Process.detach(p1)
This was my first introduction to the murky world of ruby fork and process. I read a few good blogs on this topic and will be posting more about the same topic soon.
- Person:
- Add new comment
- 197 reads
- Feed: neeraj.name
- Original article


Recent comments
1 year 23 weeks ago
1 year 23 weeks ago
1 year 25 weeks ago
1 year 27 weeks ago
1 year 42 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 46 weeks ago
1 year 48 weeks ago