在schedule.rb文件中,语句:
require "#{RAILS_ROOT}/config/environment.rb"
every "10 10 2 * * *" do
command "mysqldump -u #{@db_username} -p#{@db_password} --single-transaction #{@db_name} > #{@backup_Path}/#{@db_name}.sql 2> log/error_crontab.log"
end
当我尝试从终端执行when cmd时,出现以下错误:
config/schedule.rb:48:in `initialize': uninitialized constant Whenever::JobList::RAILS_ROOT (NameError)
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever/job_list.rb:19:in `instance_eval'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever/job_list.rb:19:in `initialize'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever.rb:16:in `new'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever.rb:16:in `cron'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever/command_line.rb:40:in `run'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever/command_line.rb:7:in `execute'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/bin/whenever:38:in `<top (required)>'
from /usr/local/bin/whenever:19:in `load'
from /usr/local/bin/whenever:19:in `<main>'
我正在使用require语句从表单中获取动态值以安排作业。请帮忙解决这个问题?
注意:我看过以下stackoverflow查询: How to detect Rails environment inside whenever
遵循此线程获取动态值,但遇到require语句的问题。 Rails - Whenever gem - Dynamic values
答案 0 :(得分:28)
当根本不需要或依赖Rails时,所以当它运行时,RAILS_ROOT没有被定义,但是因为每当schedule.rb通常保存在/config/schedule.rb中时,我们可以假设它是在rails项目中,设置我们自己的RAILS_ROOT:
# in schedule.rb
RAILS_ROOT = File.dirname(__FILE__) + '/..'
编辑:如果您确实需要加载Rails,请执行以下操作:
# in schedule.rb
# this will require config/environment and load your entire rails environment
require File.expand_path(File.dirname(__FILE__) + "/environment")
答案 1 :(得分:18)
每当开发人员已回答此问题时,请查看https://github.com/javan/whenever/issues/81
Javan每当不再尝试加载Rails环境时。但是,无论何时执行,它都会自动将路径变量设置为目录。这应该是相同的:
set :output, "#{path}/log/cron.log"
答案 2 :(得分:3)
在Rails 4中尝试:
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
在schedule.rb文件中。 这样,您还可以访问所有活动记录模型和初始化程序。