views:

71

answers:

3

I am implementing a poller service whose interface looks like this.

poller = Poller.new(SomeClass)
poller.start
poller.stop

The start method is supposed to continuously start hitting an http request and update stuff in the database. Once started, the process is supposed to continue till it is explicitly stoped.

I understand that implementation of start needs to spawn and run in a new process. I am not quite sure how to achieve that in Ruby. I want a ruby solution instead of a ruby framework specific solution (Not rails plugins or sinatra extensions. Just ruby gems). I am exploring eventmachine and starling-workling. I find eventmachine to be too huge to understand in short span and workling is a plugin and not a gem. So it is a pain get it working for Ruby application.

I need guidance on how do I achieve this. Any pointers? Code samples will help.

Edit

Eventmachine or starling-workling solution would be preferred over threading/forking.

A: 
class Poller

    def start
       @thread = Thread.new { 
           #Your code here
       } 
    end


    def stop
       @thread.stop
    end

end
floatless
+1  A: 

Can't you use the example from Process#kill:

class Poller
  def initialize klass
    @klass = klass
  end

  def start
    @pid = fork do
      Signal.trap("HUP") { puts "Ouch!"; exit }
      instance = @klass.new
      # ... do some work ...
    end
  end

  def stop
    Process.kill("HUP", @pid)
    Process.wait
  end
end
Mladen Jablanović
A few questions.1) What is the purpose of the code `Process.wait`?2) Is forking safe in ruby. Asking because I have read/heard/learnt that processes and threading in ruby are not so reliable. Can you please justify your solution?
Chirantan
1) I guess that the child process is not terminated as soon as you call `kill`, there's a `trap` call which should do the cleanup in the child process and it could take some time. `wait` is there to wait for the very exit. 2) Define _safe_. Forking works as in any other language, it is feature of OS, not of a language.
Mladen Jablanović
+1 Your solution has worked for now.
Chirantan
A: 

Have you considered out the Daemons gem?

Swanand