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

Whenever Gem执行失败求助:bundle exec whenever报错未初始化常量Rails

问题:执行bundle exec whenever报错未初始化常量Rails

报错信息

$ bundle exec whenever
bundler: failed to load command: whenever (/home/cgarndt/.rbenv/versions/3.0.0/bin/whenever)
config/schedule.rb:35:in `initialize': uninitialized constant #<Class:#<Whenever::JobList:0x0000555d07619838>>::Rails (NameError)
    from /home/cgarndt/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/whenever-1.0.0/lib/whenever/job_list.rb:25:in `instance_eval'
    ... ... ...

开发环境配置

  • Ubuntu 22.04 LTS
  • rbenv
  • Ruby 3.0
  • Rails 7.0.4
  • whenever (1.0.0)

已执行操作及schedule.rb内容

已执行bundle exec wheneverize .生成schedule.rb,内容如下:

# Need the below for Cron to pick up rbenv user version within Unix-user/application.
# Vs w/o the below line then Cron uses rbenv system version.
env :PATH, ENV['PATH']

# Compare Person API CALS People data to CALS-2 People data
if Rails.env.staging?
  every :monday, at: '7:50am' do
    runner "CjComparePersApiCalsPeople::Start.execute"
  end
endif ::Rails.env.production?
  every :monday, at: '8:05am' do
    runner "CjComparePersApiCalsPeople::Start.execute"
  end
end

解决方案

1. 修复schedule.rb语法错误

原代码中endif ::Rails.env.production?是错误的Ruby语法,可修改为两种形式:

方式一:拆分独立判断

if Rails.env.staging?
  every :monday, at: '7:50am' do
    runner "CjComparePersApiCalsPeople::Start.execute"
  end
end

if ::Rails.env.production?
  every :monday, at: '8:05am' do
    runner "CjComparePersApiCalsPeople::Start.execute"
  end
end

方式二:用elsif简化逻辑

if Rails.env.staging?
  every :monday, at: '7:50am' do
    runner "CjComparePersApiCalsPeople::Start.execute"
  end
elsif Rails.env.production?
  every :monday, at: '8:05am' do
    runner "CjComparePersApiCalsPeople::Start.execute"
  end
end

2. 加载Rails环境

在schedule.rb开头添加代码,确保whenever能识别Rails常量:

require File.expand_path('../config/environment', __FILE__)

# Need the below for Cron to pick up rbenv user version within Unix-user/application.
# Vs w/o the below line then Cron uses rbenv system version.
env :PATH, ENV['PATH']

# ... 后续原有代码 ...

3. 可选:指定环境执行命令

执行whenever时明确指定环境,确保加载对应配置:

bundle exec whenever -e staging
# 或
bundle exec whenever -e production

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:10:16