问题
In schedule.rb file, the statement:
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 i try to execute the whenever cmd from terminal, getting the following error:
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>'
i am using the require statement to get the dynamic values from the form to schedule the job. Please help to solve this issue?
Note: i have seen the following stackoverflow queries: How to detect Rails environment inside whenever
Following this thread to get dynamic values, but facing problem with require statement. Rails - Whenever gem - Dynamic values
Ruby/Rails - Whenever gem - Loop cron tasks
config file in schedule.rb with Rails Whenever gem?
回答1:
Whenever doesn't require or depend on Rails at all, so when it runs, RAILS_ROOT is not defined, however because whenever's schedule.rb is generally kept in /config/schedule.rb, we can make an assumption that it is in a rails project, and set our own RAILS_ROOT like this:
# in schedule.rb
RAILS_ROOT = File.dirname(__FILE__) + '/..'
Edit: in the case that you actually need Rails loaded, do this:
# in schedule.rb
# this will require config/environment and load your entire rails environment
require File.expand_path(File.dirname(__FILE__) + "/environment")
回答2:
The whenever developer already answered this question, check this out https://github.com/javan/whenever/issues/81
Javan Whenever no longer attempts to load your Rails environment. However, it does automatically set a path variable to the directory whenever was executed from. This should work just the same:
set :output, "#{path}/log/cron.log"
回答3:
In Rails 4 try with:
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
in your schedule.rb file. This way you also have access to all your active-record models and initializers.
来源:https://stackoverflow.com/questions/7978177/whenever-gem-schedule-rb-file-doesnt-recognize-rails-root-variable