Search code examples
ruby-on-railsrubycronscheduled-taskssidekiq

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


I am trying to make a method run every minute using the sidekiq scheduler. But when I try to execute the cron job, my database is not accessible.

This is my controller code

#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

When I try to execute the cron job like this,

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

I get an error saying

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>'

Is this error because of the Redis server? If so, how can I access my existing models and database?


Solution

  • The problem is in your sidekiq command:

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

    You can't directly require a specific controller like that since it doesn't know where the superclass is i.e. your controller doesn't explicitly require the application_controller.rb file, hence that error.

    Sidekiq's usage states:

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

    This is suggesting you give it the directory where your Rails application is, not an individual controller. But, if you run the sidekiq command from the directory of your Rails app then:

    you do not need the -r option

    Simply run sidekiq