1

I have written a Rails application which have a db of set of students and that db gets updated on daily basis with the help of a rake task. I mean this task updates entry corresponding to each student id, i.e. first student id 1 then for student id 2 and so on like following.:

task :update_db => :environment do
   student_ids = Student.map{|x|x.id}
   student_ids.each do |sid|
    begin
      StudentHelper.update_db_entry(sid)
    rescue Exception => e
      Rails.logger.info "#{e.message}"
      Rails.logger.info "#{e.backtrace.inspect}"
    end
   end
end

Here entry of a student in the db is independent of other students so it appears that we can update the entry of more than one student at the same time. I think this is only possible with mutithreading.

I am not getting any clue how to proceed, I have no idea how to implement multithreading in ruby on rails application.

Joy
  • 4,197
  • 14
  • 61
  • 131
  • Multithreading is probably not necessary here unless you are having a serious issue with performance. Also a large number of threads are going to tie up your database, which means other applications using the database will be less responsive – Slicedpan Mar 14 '14 at 11:40

2 Answers2

0

To spawn a new thread and make it do some work using AR models, use the following code:

thread = Thread.new do 
  ActiveRecord::Base.connection_pool.with_connection do
    #your code updating students here
  end
end

You'll need to split the id numbers into equal parts and assign a part to each thread. Since each thread will require a database connection from the pool, you can quickly exhaust the available connections so don't use too many. The number of db connections in the pool are set in config/database.yml.

You can use the join method of the thread object to wait until that thread is finished, in case you want to perform further actions once all records are processed.

Slicedpan
  • 4,995
  • 2
  • 18
  • 33
0

If you are using "classic" Ruby then threads are not actually executed in parellel, they running in one ruby process in OS. For a real parallelism you should use processes

see more here stackoverflow

Community
  • 1
  • 1
lx00st
  • 1,566
  • 9
  • 17