1

Where is the proper place to place eventmachine code in a rails app?

For example:

class Test < EventMachine::Connection
  def post_init
    send_data "test"
  end

  def receive_data(data)
  end
end

EventMachine.run {
  EventMachine.connect "someplace.com", 80, Test
}

Now say I required this for one of my controllers my app will just continue waiting while this runs.

How can I have this run in the background in a rails app?

tbuehlmann
  • 9,032
  • 5
  • 27
  • 33
Brian
  • 5,951
  • 14
  • 53
  • 77
  • Are you running Rails with an EM based webserver like [Thin](http://code.macournoyer.com/thin/) or [Rainbows!](http://rainbows.rubyforge.org/)? – tbuehlmann Dec 07 '11 at 09:57
  • This answer may be useful for you: http://stackoverflow.com/questions/5799406/how-do-you-spawn-an-eventmachine-inside-a-rails-app – Blue Smith Sep 18 '12 at 03:49

2 Answers2

1

There is no perfect solution for that. It depends on how you designed your app.

You could put this code in /lib, have a method "start_event_machine" and call this method in a rake task. Then add stuff like monit on your server to make sure it runs fine.

marcgg
  • 65,020
  • 52
  • 178
  • 231
0

You need to look into either Resque or DelayedJob for backgrounding tasks. I don't think that EventMachine is the best solution for trying to background jobs within Ruby on Rails.

The other option is to have a separate process for handling the async work, passing the task down a message queue like RabbitMQ or something similar.

Sean Hill
  • 14,978
  • 2
  • 50
  • 56