rails Taskの実行(バッチの実行)

本稿について

本稿はサイト運営者が学んだことなどを記したメモの内容です。
全てが正確な情報とは限りません。ご注意ください。また修正するべき点は適時修正していきます
Taskの生成
rails g task test_task

実行コマンドの確認
$ bundle exec rails -T

実行コマンド
$ bundle exec rails "report:hourly[15]"

task処理
namespace :report do
  desc '1時間毎のレポート'
  task :hourly, ['target_hour'] => :environment do |task, args|
    report = Report.new(Time.zone.now, :hourly, args) # args => 15
    report.export_csv
  end
end

入れ子にする場合
namespace :temporary do
  namespace :test_task do
    desc ‘入れ子のタスクを実行する'
    task execute: :environment do |task, args|
       pp “タスクの実行"
    end
  end
end

入れ子を実行
$ bundle exec rails temporary:test_task:execute

Back