Reputation: 20004
I have a ruby script which takes some fare amount of time to finish running. I have tried running this code:
get "/run" do
exec "ruby #{"/home/user/script.rb"} &"
redirect '/'
end
But what happens is that, my Sinatra script then waits until the process is finished. How to execute that script so it is left to run in the background, and my Sinatra script just redirects back?
Thanks!
Upvotes: 1
Views: 1767
Reputation: 631
I encountered a similar problem, and below is what worked for me.
get "/run" do
task = Thread.new {
p "sleeping for 10 secs"
sleep(10)
p "woke up :)"
}
redirect '/'
end
Upvotes: 4
Reputation: 11228
You have to fork and detach the child process.
require 'rubygems'
require 'sinatra'
get "/" do
"index"
end
get "/run" do
Process.detach(fork{ exec "ruby script.rb &"})
redirect '/'
end
let's say script.rb is like
p "sleeping for 10 secs"
sleep(10)
p "woke up :)"
This works for me.
Upvotes: 3