【问题标题】:Cannot pass params to sidekiq无法将参数传递给 sidekiq
【发布时间】:2015-04-18 09:27:44
【问题描述】:

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

控制器

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

工人

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

【问题讨论】:

标签: ruby-on-rails ruby redis sidekiq


【解决方案1】:

在您的工作人员中:

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

然后在你的控制器中:

CallLogWorker.perform_async(params)

因此,您将散列参数从控制器解析到工作程序中,然后在您的工作程序中引用它。

通常认为将传递到 Sidekiq 作业的数据尽可能小是一种好的做法 - see here 以获得最佳做法。所以你可以更进一步,拥有:

在您的工作人员中:

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

在你的控制器中:

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

【讨论】:

    猜你喜欢
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多