ruby-on-rails - 无法将参数传递给 sidekiq

标签 ruby-on-rails ruby redis sidekiq

我正在为 Controller 操作构建一个 worker,但由于我在 perform 方法中调用参数,sidekiq 无法启动。关于如何让它发挥作用的任何想法?

Controller

def call_warrants_with_date_range
  CallLogWorker.perform_async(params[:call_log])
  redirect_to call_logs_path, notice: 'Calls were successfully made.'
end

worker

class CallLogWorker
  include Sidekiq::Worker

  def perform(params[:call_log])
    client         = Twilio::REST::Client.new TWILIO_ACCOUNT_SID, TWILIO_ACCOUNT_AUTH_TOKEN
    start_date         = params[:call_log][:warrant_start_date]
    end_date           = params[:call_log][:warrant_end_date]
    query = "SELECT people.id, warrants.warn_type, warrants.warn_date_issued, phone_numbers.phone_number 
    FROM people
    LEFT OUTER JOIN warrants ON people.id = warrants.person_id
    LEFT OUTER JOIN phone_numbers ON people.id = phone_numbers.person_id
    WHERE warrants.warn_date_issued BETWEEN ? AND ? AND warrants.warn_type = 'AW'"

    @numbers = CallLog.find_by_sql(["#{query}", start_date, end_date])
    @numbers.each do |dial|
      begin
       call = client.account.calls.create(
       :from => TWILIO_PHONE_NUMBER,
       :to => dial.phone_number,
       :url => 'http://twimlets.com/echo?Twiml=hello%20this%20is%20a%20test%20call%20please%20hang%20up&'
      )

       CallLog.create!({ phone: dial.phone_number, status: call.status, 
       warrant_start_date: start_date, warrant_end_date: end_date, person_id: dial.id})
       Note.create!({ body: call.status, person_id: dial.id })
    rescue Exception => e
       CallLog.create!({ phone: dial.phone_number, status: call.status, exception: e.to_s,
       warrant_start_date: start_date, warrantend_date: end_date, person_id: dial.id})
       Note.create!({ body: e.to_s, person_id: dial.id })
    end
  end
 end
end

最佳答案

在你的工作人员中:

def perform(params)
   start_date         = params[:call_log][:warrant_start_date]
   end_date           = params[:call_log][:warrant_end_date]
   ...etc
end

然后在你的 Controller 中:

CallLogWorker.perform_async(params)

因此,您正在将哈希参数从 Controller 解析到工作程序中,然后在您的工作程序中引用它。

将传递给 Sidekiq 作业的数据保持尽可能小通常被认为是一种好的做法 - see here最佳实践。所以你可以走得更远:

在你的工作人员中:

def perform(start_date, end_date)
   ...job content
end

在你的 Controller 中:

CallLogWorker.perform_async(
  params[:call_log][:warrant_start_date],  
  params[:call_log][:warrant_end_date]
)

关于ruby-on-rails - 无法将参数传递给 sidekiq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28565658/

相关文章:

ruby-on-rails - 更改默认 Rails text_area 辅助行/列

ruby-on-rails - 在 Jenkins CI 服务器上运行 Jasmine

node.js - Nodejs 连接到 AWS ElasticCache 复制组

ruby-on-rails - Rubymine 弃用警告

ruby-on-rails - 如何使用 sort_by 按字母顺序排序,然后按数字排序,然后按特殊字符排序

ruby - ruby 中的单元测试不将结果打印到控制台

python - Adobe Brackets 和运行 Ruby/Python 程序

ruby-on-rails - 通过在应用程序启动时启动工作人员来初始化延迟作业 gem

search - REDIS 哈希 HMSET 中的 COUNT 和 SEARCH

spring - Spring Data Redis 模板中没有 maxlen 选项来限制流大小