Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Aug 01

Fork with spawn

Posted by Sandro Paganotti in Ruby on Rails - comments are closed digg this add to delicious

During the development of our current project we needed to handle a very long task (4 minutes). After a bit of googling i found spawn by Tom Anderson. Here’s how it works:

Spawn let you fork (or thread) a block of code by simply pass it as a parameter to a ‘spawn’ function:


  spawn do
   # very long long task
  end

what spawn do (when used with ‘fork’) is recreate an ActiveRecord Connection inside a fork method and then execute your block of code. You can also set the priority of the process being create with the option ‘nice’:


  spawn(:nice => 7) do
    # do something
  end

Finally you can wait the end or your child processes with the method Spawn::wait() (I took this example from the official readme):


  N.times do |i|
    # spawn N blocks of code
    spawn_ids[i] = spawn do
      something(i)
    end
  end
  # wait for all N blocks of code to finish running
  wait(spawn_ids)

I haven’t tried to use spawn with threads but as far as I’ve tested it with fork, it works perfectly.

Comments

  • kain

    Posted on August 07

    try also BackgroundJob (Bj)
  • Skip Hire

    Posted on August 14

    I love how RoR seems to be so lightweight. I am currently contemplating moving over to RoR from PHP.

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory