Warm tip: This article is reproduced from stackoverflow.com, please click
ruby sinatra

Running Sinatra app inside Thread doesn't work

发布于 2020-03-31 22:59:32

I'm trying to run a Sinatra app in a new Thread in order to also run some other thing inside my script but when I do:

require 'sinatra/base'

class App < Sinatra::Base
...some routes...
end

Thread.new do
  App.run!
end

Nothing happens and Sinatra server is not started. Is there anything I'm missing in order to achieve this?

Questioner
xmarston
Viewed
19
xmarston 2020-01-31 19:55

Finally I run the other ruby process in a Thread but from Sinatra application and it works just fine.

class App < Sinatra::Base
    threads = []

    threads <<
      Thread.new do
        Some::Other::Thing
      rescue StandardError => e
        $stderr << e.message
        $stderr << e.backtrace.join("\n")
      end

    trap('INT') do
      puts 'trapping'
      threads.each do |t|
        puts 'killing'
        Thread.kill t
      end
    end

    run!
end

And I added a control when Sinatra app is exited also kill the open thread.