heroku: how to avoid timeout when post some data to heroku
I have a ROR app on heroku.There a开发者_如何学编程re 8 optional text fields on the app, user can fill it or let it be empty according to their requirements.
The more text fields user fill, the more processes my app needs to do. My app will process the request more than 30s if there are more than 5 fields be filled and it will cause Heroku timeout.
Is there any solution to deal with this problem?
I heard that using javascript and ajax can divide a request into two parts, I think it will avoid the timeout problem. However, I am not sure how to do it.
Thanks!
It's not acceptable to have such delay from user point of view.
You should delegate the form handling to a worker using Resque or DelayedJob.
You just need to do the processing as a background job. On Heroku it's super easy. Use Resque + Redis, but you can also use DelayedJob. Resque (built by github) is a queueing layer on top of Redis (a key value store). It's much easier to scale than doing queuing with DelayedJob, but either way works.
- First, install the free Heroku Redis to Go addon.
- Then just follow Redis To Go's Resque with Redis on Heroku blog Post to setup the gems and such.
Once that's setup, here's all you need to do:
- Post the form data.
- Save it unprocessed to be processed later.
- Tell Resque that you've added something to the queue.
If your form is a user creation form, the code might be like this:
module SaveUser
@queue = :save_user
def perform(attributes = {})
user = User.create(attributes)
user.process! if user && !user.processed_everthing?
end
end
def create
Resque.enqueue(SaveUser, params[:user])
end
… you could also write it like the following (storing only the id
in the queue, not the params)
module SaveUser
@queue = :save_user
def perform(id)
user = User.find(id)
user.process! if user && !user.processed_everthing?
end
end
def create
user = User.create(params[:user])
Resque.enqueue(SaveUser, user.id)
end
By queuing up everything, the user will be almost immediately taken to the next page.
If the user needs to see the result of the processing immediately on the next page, however, you're just going to have to figure something else out.
精彩评论