You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Sidekiq-Cron创建定时任务时出现Rufus::Scheduler::CronLine未初始化错误

Fixing "uninitialized constant Rufus::Scheduler::CronLine" in sidekiq-cron with Rails 5.2.0

That error pops up because the Rufus::Scheduler::CronLine class—critical for sidekiq-cron to parse cron expressions—isn't loading properly, and this almost always ties back to gem version mismatches or missing dependency setup. Let's work through fixing this step by step:

1. Align gem versions for compatibility

Rails 5.2.0 plays best with specific older releases of sidekiq and sidekiq-cron. Update your Gemfile to use versions that work together seamlessly:

# Gemfile
gem 'sidekiq', '~> 5.2.8' # Stable release built for Rails 5.2 compatibility
gem 'sidekiq-cron', '~> 1.10.0' # Matches sidekiq 5.x and includes the correct rufus-scheduler dependency

Run bundle install to pull in the right versions, then restart your Rails server and Sidekiq process—this ensures all dependencies load correctly from the start.

2. Explicitly load sidekiq-cron in your initializer

Create or update config/initializers/sidekiq.rb to make sure sidekiq-cron (and its Rufus dependencies) are loaded when your app starts:

# config/initializers/sidekiq.rb
require 'sidekiq'
require 'sidekiq/cron'

# Optional but recommended: Load cron jobs from a YAML file for persistence
Sidekiq::Cron::Job.load_from_hash YAML.load_file(Rails.root.join('config', 'schedule.yml')) if Rails.env.production?

This prevents the "uninitialized constant" error by ensuring Rufus's cron parsing logic is available before you try to create jobs.

3. Recreate the job in a fresh console

After restarting your Rails console, try creating the job again:

job = Sidekiq::Cron::Job.new(
  name: 'TestWorker_Job',
  cron: '*/2 * * * *',
  klass: 'PriceWorker'
)

If the error is gone, check job.errors to confirm no other issues, then run job.save to persist the job.

4. Bonus: Use a schedule file for long-term persistence

Creating jobs via the console won't survive app restarts. For production, define your cron jobs in config/schedule.yml:

# config/schedule.yml
TestWorker_Job:
  cron: "*/2 * * * *"
  class: "PriceWorker"
  queue: default

The initializer we added earlier will load these jobs automatically when your app starts—this is the standard, maintainable approach.


内容的提问来源于stack exchange,提问作者Max Stephen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:42:51