问题
I want to pass different arguments to every method and need to run all methods parallel using rake task
Here is rake task calling example
Rake::Task['test:sync'].invoke(user.id, user.address)
Rake::Task['test:sync'].invoke(user.id, user.address)
Rake::Task['test:sync'].invoke(user.id, user.address)
I have seen the multitask example like this
multitask :copy_files => [:copy_src, :copy_doc, :copy_bin] do
puts "All Copies Complete"
end
Here they are calling with the task name alone. But in my case i want to pass task name with parameters . How can i achieve it.
回答1:
Extract the functionality into its own method (foo
) and dynamically declare rake tasks with the arguments (arg1
,arg2
) baked into the task name itself. Then declare a multitask
and invoke it. All calls to foo
will be run in parallel.
def foo(arg1, arg2)
thread_id = Thread.current.object_id.to_s[-4..-1]
10.times do |i|
sleep rand
puts "[#{thread_id}] (#{arg1}) (#{arg2}) (#{i})"
end
end
task :parallel_foos do
arg1s = (1..4).map { sprintf('%.4f', rand) }
arg2s = %w{red green blue yellow}
arg_pairs = arg1s.zip(arg2s)
# dynamically declare unique rake tasks
arg_pairs.each do |arg_pair|
task arg_pair.to_s do
foo(*arg_pair)
end
end
multitask :_parallel_foos => arg_pairs.map(&:to_s)
Rake::MultiTask[:_parallel_foos].invoke
end
>> rake parallel_foos
[2460] (0.4510) (blue) (0)
[4820] (0.5997) (yellow) (0)
[4820] (0.5997) (yellow) (1)
[2980] (0.3482) (red) (0)
[2980] (0.3482) (red) (1)
[2100] (0.2251) (green) (0)
[2980] (0.3482) (red) (2)
[4820] (0.5997) (yellow) (2)
[2460] (0.4510) (blue) (1)
[2980] (0.3482) (red) (3)
[4820] (0.5997) (yellow) (3)
[2100] (0.2251) (green) (1)
[2980] (0.3482) (red) (4)
[2100] (0.2251) (green) (2)
[2460] (0.4510) (blue) (2)
[2100] (0.2251) (green) (3)
[4820] (0.5997) (yellow) (4)
[2460] (0.4510) (blue) (3)
[2980] (0.3482) (red) (5)
[4820] (0.5997) (yellow) (5)
[2460] (0.4510) (blue) (4)
[2980] (0.3482) (red) (6)
[2100] (0.2251) (green) (4)
[2460] (0.4510) (blue) (5)
[4820] (0.5997) (yellow) (6)
[2100] (0.2251) (green) (5)
[2980] (0.3482) (red) (7)
[2460] (0.4510) (blue) (6)
[4820] (0.5997) (yellow) (7)
[2980] (0.3482) (red) (8)
[2100] (0.2251) (green) (6)
[4820] (0.5997) (yellow) (8)
[2460] (0.4510) (blue) (7)
[2100] (0.2251) (green) (7)
[2980] (0.3482) (red) (9)
[2460] (0.4510) (blue) (8)
[4820] (0.5997) (yellow) (9)
[2460] (0.4510) (blue) (9)
[2100] (0.2251) (green) (8)
[2100] (0.2251) (green) (9)
来源:https://stackoverflow.com/questions/24446029/how-to-pass-different-arguments-in-rake-multitask