Rails 5:在将 Sidekiq 调度程序与 Redis 结合使用时无法访问我的数据库

Rails 5: Unable to access my database while using Sidekiq scheduler with Redis

我正在尝试使用 sidekiq 调度程序每分钟创建一个方法 运行。但是当我尝试执行 cron 作业时,我的数据库无法访问。

这是我的控制器代码

#product_controller.rb

require 'sidekiq-scheduler'

class ProductsController < ApplicationController
  include ApplicationHelper
  include Sidekiq::Worker

  def task
    Product.each do |product|
      product.price.push(get_price_from_link(product.flipkart_link))
      product.time.push(Time.now)
      product.save!
    end
  end

 private

  def product_params
    params.require(:product).permit(:flipkart_link, :flipkart_id, :name, :category, :image_url, :max_price, :price, :available, :target_price, :user_id)
  end
end


#sidekiq.yml

:schedule:
  cron_task:
    cron: '0 * * * * *'   # Runs once per minute
  class: ProductsController

当我尝试像这样执行 cron 作业时,

sidekiq -r ./app/controllers/products_controller.rb

我收到一条错误消息

uninitialized constant ApplicationController
/home/raghav/workspace/apps/Shotgun/app/controllers/products_controller.rb:3:in `<top (required)>'
/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:120:in `require'
/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:120:in `require'
/var/lib/gems/2.3.0/gems/sidekiq-5.0.0/lib/sidekiq/cli.rb:262:in `boot_system'
/var/lib/gems/2.3.0/gems/sidekiq-5.0.0/lib/sidekiq/cli.rb:54:in `run'
/var/lib/gems/2.3.0/gems/sidekiq-5.0.0/bin/sidekiq:12:in `<top (required)>'
/usr/local/bin/sidekiq:23:in `load'
/usr/local/bin/sidekiq:23:in `<main>'

这个错误是不是Redis服务器的问题?如果是这样,我如何访问我现有的模型和数据库?

问题出在你的 sidekiq 命令中:

sidekiq -r ./app/controllers/products_controller.rb

您不能直接要求这样的特定控制器,因为它不知道超类在哪里,即您的控制器没有明确要求 application_controller.rb 文件,因此会出现错误。

Sidekiq 的使用说明:

-r, --require [PATH|DIR] Location of Rails application with workers or file to require

这建议您将 Rails 应用程序所在的目录提供给它,而不是单独的控制器。但是,如果您 运行 来自 Rails 应用程序目录的 sidekiq 命令,那么:

您不需要 -r 选项

简直运行sidekiq