Thursday, August 18, 2011

Run rake task in background

Hey rubies,
                Some time we need immediate response at that time we have option to run functionality in background by invoking rake task.

Here is the small example

Assume we have task called 'generate_random_number' which we need to invoke in background. below is the steps for that.

Invoke the background task by

call_rake 'generate_random_number', {:initial => 10}

definition for call_rake

def call_rake(task, options = {})   
    # define rails environment as option etc...
    options[:rails_env] ||= RAILS_ENV
    # collect argument list
    args = options.map { |n, v| "#{n.to_s.upcase}='#{v}'" }         
    # invoke task from rails and generate log
    system "rake #{task} #{args.join(' ')} --trace 2>&1 >> #{RAILS_ROOT}/rake.log &"   
  end

Here is the task definition.
desc "Generate Random Number"
task :generate_random_number, [:initial] => :environment do |t, args|
    puts "here is your random number " + rand(args[:initial] ).to_s
end

This the way how task execute in background. If you have any query or suggestion then post the comment.

No comments:

Post a Comment