run multiple rake tasks simultaneously

Here’s a quick and simple tip for using threads and Rakefiles:

task :one do
  puts "start one"
  sleep 10 * rand
  puts "one done"
end
 
task :two do
  puts "start two"
  sleep 10 * rand
  puts "two done"
end
 
task :three do
  puts "start three"
  sleep 10 * rand
  puts "three done"
end
 
desc "Submit all feed to amazon for SITE"
task :do_all do
  threads = []
  %w{one two three}.each do |number|
    threads << Thread.new(number) do |my_number|
      Rake::Task[my_number].invoke
    end
  end
  threads.each { |thread| thread.join } 
end

Running it gives something like the following:

$ rake do_all
start one
start two
start three
three done
one done
two done
Share:
  • del.icio.us
  • Reddit
  • Technorati
  • Twitter
  • Facebook
  • Google Bookmarks
  • HackerNews
  • PDF
  • RSS
This entry was posted in programming, ruby, tips. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.