Independent thread use in Rails app


#1

I would like to be able to start several independent threads in my
Rails app. These threads will run as long as the Rails app is running.

  1. What is the right place to start and stop the threads? My threads
    need to run shutdown code. I’ve tried adding code like this but it
    isn’t working correctly. The debugger is getting an ABRT or TERM
    signal and I still need to shut down the database.

Signal.trap(“INT”) { threads[0].kill; database.close; server.shutdown}
%w{ABRT CLD TERM STOP QUIT}.each { |x| Signal.trap(x) {
database.close; server.shutdown } }

threads[0].kill this is the monitor thread, it will never exit unless
killed. Alternatively I could send it a message to exit.

  1. I’d like to set things up so that if WEBrick is being used the
    threads run in the same process. But if lighttpd is being used with
    multiple processes the thread only gets started in one of the fastcgi
    processes. There needs to be some mechanism to see if the process
    with the thread dies and get it started again in another fastcgi
    process.

The thread monitors the directory tree being served, if files are
copied in or removed it add/deletes them from a search database. It is
using iNotify on Linux, but other OSes offer similar monitoring APIs.
I’ll make the code public as soon as it is working, unless someone
tells me this has already been written.


Jon S.
removed_email_address@domain.invalid


#2

I would like to be able to start several independent threads in my
Rails app. These threads will run as long as the Rails app is running.

A lot of folks have worked on this sort of thing before, and the
general consensus has been that you make your life much easier by
spinning off the threads into a standalone tasks that communicate
with the Rails app using DRb or another RPC mechanism. This will free
you from worrying about the thread/fork/etc. architectures of your
chosen server model (WEBrick, mod_ruby, FCGI runners, etc.).

There’s a good introduction to DRb at http://segment7.net/projects/
ruby/drb/introduction.html.

-Ben