15

At the command line I can run multiple tasks like this

rake environment task1 task2 task3

How can I do this programmatically? I know that I can run one task like this

Rake::Task['task1'].invoke
Anthony Mastrean
  • 21,850
  • 21
  • 110
  • 188
codefinger
  • 10,088
  • 7
  • 39
  • 51

2 Answers2

19

You can call two tasks:

require 'rake'

task :task1 do |t|
  p t
end
task :task2 do |t|
  p t
end


Rake::Task["task1"].invoke
Rake::Task["task2"].invoke

I would prefer a new tast with prerequisites:

require 'rake'

task :task1 do |t|
  p t
end
task :task2 do |t|
  p t
end
desc "Common task"
task :all => [ :task1, :task2  ]
Rake::Task["all"].invoke

If I misunderstood your question and you want to execute the same task twice: You can reenable tasks:

require 'rake'

task :task1 do |t|
  p t
end
Rake::Task["task1"].invoke
Rake::Task["task1"].reenable
Rake::Task["task1"].invoke
knut
  • 27,320
  • 6
  • 84
  • 112
  • yup, i guess i just needed to invoke two tasks one after the other. – codefinger Jan 15 '12 at 17:50
  • 1
    You can also use `.execute` instead of `.invoke` if you are running the same rake task multiple times. `invoke` will only allow it to be called once unless you use `reenable`. – Joshua Pinter Jan 20 '21 at 20:50
2

Make a rake task for it :P

# in /lib/tasks/some_file.rake
namespace :myjobs do 
  desc "Doing work, son" 
  task :do_work => :environment do
    Rake::Task['resque:work'].invoke 
    start_some_other_task
  end

  def start_some_other_task
    # custom code here
  end
end

Then just call it:

rake myjobs:do_work
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
  • I was hoping to do it without creating additional rake tasks. I'm not running from the command line at all, so I would have to Rake::Task['myjobs:do_work'].invoke. I will try this. – codefinger Jan 13 '12 at 21:30
  • `Rake::Task['myjobs:do_work'].invoke` works as well. Just nice to consolidate things, IMO. Easier to maintain in the future – iwasrobbed Jan 13 '12 at 21:34