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
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
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
No comments:
Post a Comment