【问题标题】:DelayedJob email where to have 'who to email' logicDelayedJob 电子邮件在哪里有“给谁发电子邮件”逻辑
【发布时间】:2012-06-19 03:05:20
【问题描述】:

在我的app 中,我的某些事件会触发大量电子邮件 (~100)。显然,立即发送它们不是一种选择,因此我使用 DelayedJob 将它们排队并在处理请求后发送它们。我现在发现确定要发送电子邮件的 100 人的逻辑非常繁重,以至于需要一段时间才能运行,所以我也想延迟该过程。 这个逻辑应该去哪里? (模型?邮件程序?) 从模型发送邮件感觉不对。这里有最佳做法吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 email delayed-job


    【解决方案1】:

    您应该编写一个代表工作的类。不是模型类,也不是控制器类:作业类。

    # app/jobs/mail_job.rb
    class MailJob
      attr_accessor :first_option, :second_option
    
      def initialize(first_option, second_option)
        self.first_option = first_option
        self.second_option = second_option
      end
    
      def perform
        accounts = Account.where("some_key" => first_option).to_a
        # more complicated stuff goes here
        accounts.each do |account|
          AccountMailer.hello_message(account).deliver
          account.mark_hello_delivered!
        end
      end
    end
    
    job = MailJob.new(params["first"], params["second"])
    Delayed::Job.enqueue(job)
    

    【讨论】:

    • 哇。让我花一分钟的时间思考一下。所以这不是ActionControllerActiveRecord 孩子,而是用我的应用程序初始化的独立类?我需要将这个文件加载到我的application.rb 中,对吗?我想我喜欢它。
    • 没错。如果它在app/**/* 中,则不需要在 application.rb 中使用它,因为其中的所有内容都是可自动重新加载的。只需确保类名与文件名匹配即可。
    • 请注意,最后两行是您将在控制器操作中用于将此类作业排入队列的内容。它们不是作业类本身的一部分,而只是如何使用它的示例。
    猜你喜欢
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    相关资源
    最近更新 更多