开发者

How can Rails observers and callbacks be handled asynchronously (in a different thread)?

Observers and Callbacks on Rails models operate on the same thread and block the request until they return.

For example, if I have a Photo model and I queue a resizing job in the after_create callback or observer, the request doesn't finish until an entry is made in the queue (which can sometimes be slow if I am using Amazon SQS for queuing).

Same holds true for Callbacks on Rails cont开发者_高级运维rollers. If I have to run maintenance like cache management or store analytics the request doesn't finish until the callback ends.

Is there a Rails way to run the code inside a callback (Model or Controller) or observer in a different thread so the request isn't stalled?


A couple of the popular ways to run code in the background out of the request/response cycle is currently delayed_job and resque

delayed_job uses your database to queue up background processing jobs, and resque uses Redis.

I've used both and they both work great, read the documentation to see which might suit your case best.

This doesn't automatically make your observers and callbacks run in the background but it makes it pretty easy to do that, and more. This technique is very widespread and production battletested in the Rails community.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜