How to run a very small amount of code asynchronously?

我与影子孤独终老i 提交于 2019-12-24 16:57:54

问题


I'd like to run a small amount of code asynchronously in my rails application. The code logs some known information. I'd like this task to not block the rest of the response from my app. The operation is way too lightweight and frequent for it to be done as a delayed job tasks.

I'm thinking to just use:

Thread.new do
  # my logging code
end

and call it a day. Is this achieving what I want it to achieve? Are there any drawbacks?


回答1:


Aside from handling some baseline resource contention things, this should be sufficient. The database resource comes to mind if you're logging there...a file if you're logging there. But the basic approach is fine I would think. Simpler is better...




回答2:


It may be overkill for your particular usage, but have you considered using some form of Message Queuing Middleware such as STOMP, AMQP, OpenWire or even Jabber?

The basic outline (pseudo-code!) would be:

s = client.create_connection(user,pass,server_ip,port)
s.message_send("Log Message Goes Here")

You would then have at least one "consumer" at the other end of the message queue which would write the log message to a file/database/chatroom/IRC Channel/whatever-you-want-really-it's-all-code... :)

It would also mean that if in future you wanted to hand-off high-intensity processing jobs (invoice generation for example) you would already have the infrastructure in place to do so.

Also if you're looking for a really easy Messaging server, I recommend RabbitMQ - it's written in Erlang (but don't let that put you off!) and is very easy to setup.

This is my first post so I can't post any more than two links, but I've published links to all the technologies mentioned above in a gist @ https://gist.github.com/1090372



来源:https://stackoverflow.com/questions/6736051/how-to-run-a-very-small-amount-of-code-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!