1

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!

UmNyobe
  • 22,539
  • 9
  • 61
  • 90
spacemonkey
  • 19,664
  • 14
  • 42
  • 62

2 Answers2

4

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
omarshammas
  • 631
  • 4
  • 18
3

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.

intellidiot
  • 11,108
  • 4
  • 34
  • 41
  • actually it doesn't work for me, it worked in a plain script though... what happens is browser waits for the page to respond, an in the terminal you can see the output of the script – spacemonkey Apr 14 '11 at 09:03