26
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rakeタスク作成

Posted at

参考


タスク作成

rails g task send_mail
----------
      create  lib/tasks/send_mail.rake
----------
  • lib/tasks/send_mail.rake
namespace :send_mail do
  desc "メール送信"

  task :mail_magazine, [:target, :id] => :environment do |task, args|
    target = args[:target]
    id     = args[:id]

    mail_maga = MailMagazine.where( id: id ).first
    raise "MailMagazine Not Found" if mail_maga.blank?

    if target == "all"
      users = User.all

      users.each_with_index(1) { |user, i|
        begin
          UserMailer.mail_magazine( user.email, mail_maga ).deliver
          puts "[ #{i} : #{user.email} ]"
        rescue Exception => e
          puts "[ ---------- Exception ---------- ]" ; e.tapp ;
        end
      }

      mail_maga.update_attributes!( target: target, last_sent_at: Time.now )
    else
      begin
        UserMailer.mail_magazine( target, mail_maga ).deliver
        result = mail_maga.update_attributes!( target: target, last_sent_at: Time.now )
        puts "[ ---------- result ---------- ]" ; result.tapp ;
      rescue Exception => e
        puts "[ ---------- Exception ---------- ]" ; e.tapp ;
      end
    end
  end
end
  • タスク確認
rake -T | grep send_mail:mail_magazine
----------
rake send_mail:mail_magazine[target,id]  # メール送信
----------
  • ローカル実行
rake send_mail:mail_magazine["aaa@gmail.com",1]

※カンマの後にスペースを入れるとエラー

rake send_mail:mail_magazine["aaa@gmail.com",1]   # => OK
rake send_mail:mail_magazine['aaa@gmail.com',1]   # => OK
rake send_mail:mail_magazine['aaa@gmail.com', 1]  # => NG
rake send_mail:mail_magazine["aaa@gmail.com", 1]  # => NG

Heroku

  • Heroku用設定

※この設定が無いとモデルが読み込めない「uninitialized constant MailMagazine」エラー

config/environments/production.rb

  # Enable threaded mode => For Heroku
  config.threadsafe!
  config.dependency_loading = true if $rails_rake_task
  • Heroku実行
heroku run rake send_mail:mail_magazine["aaa@gmail.com",1]
26
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?