Sergey
Sergey

Reputation: 49788

Run code after after the page is rendered to the user (Sinatra)

I'm looking for a way to run some slow code after after the page is rendered to the user. Concretely, I'd like to be able to do something like this:

get '/fast-action' do
  compute_after_render { put some slow code here }
  'request successful'
end

I thought about inserting the information about the computation into the database. And then running something like rufus scheduler that would be checking if there is something to compute once a minute.
But I wouldn't want the user to wait for the database to complete the insertion.

Is there any way to make Sinatra run some code after after the page is rendered to the user?

Upvotes: 1

Views: 490

Answers (3)

searsaw
searsaw

Reputation: 3632

I suggest you look into side jobs. I like to use the Sidekiq gem for this. It uses Redis to store jobs that need to be run and checks it every once and a while. It's totally configurable and all that. I highly recommend it if you're running jobs that can be done later, such as sending email, processing images and such, and running long processes.

Upvotes: 1

Esse
Esse

Reputation: 3298

You can use streaming responses:

get '/fast-action' do
  stream do |out|
    out << 'request successful'
    put some slow code here
    out << " "
  end
end

Be aware though, that server thread will be blocked for the duration of that request (and of course execution of slow code).

Upvotes: 1

B Seven
B Seven

Reputation: 45941

Yes, one quick and easy way is to start a new thread:

get '/fast-action' do
  body 'request successful'
  Thread.new{ slow code }
end

Upvotes: 2

Related Questions