我正在使用gem创建一个cron作业。这个cron作业需要定期在我的rails应用程序上运行一个帮助方法。这个辅助方法检查我的模型的每个实例,并决定是否更新它。
/app/helpers/auctions_helper.rb:
module AuctionsHelper
def self.checkForExpiredAuction
# method to update each auction that has expired
puts "There are currently #{Auction.count} auctions."
@auctions = Auction.all
@auctions.each do |auction|
if auction.end_time > Time.now.utc
auction.price = 1000000
auction.save
puts "just updated #{auction.product} auction"
end
end
puts "just updated any auctions that had expired"
end
end
schedule.rb:
set :output, "log/cron_log.log"
every 1.minute do
runner "AuctionsHelper.checkForExpiredAuction"
end
创建以下cronjob:
# Begin Whenever generated tasks for: bestBay
* * * * * /bin/bash -l -c 'cd /home/bestbay && script/rails runner -e production '\''AuctionsHelper.checkForExpiredAuction'\'' >> log/cron_log.log 2>&1'
# End Whenever generated tasks for: bestBay
我遇到的问题是辅助方法无法访问表'拍卖'。来自我的cron_log.log:
Could not find table 'auctions' (ActiveRecord::StatementInvalid)
这对辅助方法本身来说似乎不是问题。如果我从终端运行:
rails runner AuctionsHelper.checkForExpiredAuction
我从puts消息中获得了一组很好的输出。那么为什么我的cronjob不能访问我的模型/表?
答案 0 :(得分:1)
基本问题是cron没有像我刚打开shell提示时那样调整相同的环境变量。我还有一个.rvm文件正在加载我的ruby环境并且每次进入主应用程序目录时都会被设置。我终于不得不这样做了:
# set the cron log location
set :output, {:error => '/home/jason/bestbay/log/cron_error.log', :standard => '/home/jason/bestbay/log/cron_status.log'}
set :job_template, "bash -i -c ':job'"
env :PATH, ENV['PATH']
every 1.minute do
#command "echo $PATH" # confirm shell variable PATH was loaded
#command "cd #{path}" # this is not needed
#command "pwd" # visualize current directory
#command "rvm current" # visualized default ruby version and gemset
command "rvm use ruby-1.9.3-p194@cmucourse" # set desired gemest
#command "rvm current" # visualize proper gemset load
runner "AuctionsHelper.checkForExpiredAuction", :environment => 'development' # run method
end
我包括已注释掉的命令,因为它们确实帮助我想象了当cron运行时发生的事情。
答案 1 :(得分:0)
我认为默认情况下,跑步者将在RAILS_ENV=development
中运行,而cron线路连接在“生产”环境中运行。
试试这个:
RAILS_ENV=production rails runner AuctionsHelper.checkForExpiredAuction
如果你得到同样的错误,那就是问题
要进行测试,请将您的生产环境指向您的开发,在database.yml
中production:
development
答案 2 :(得分:0)
whatever
默认为生产,并且会默认查找生产数据库。要更改此行为,您可以更新 crontab 并将其设置为 development:
whenever --update-crontab --set environment='development'
希望这能节省一些人的时间,因为它让我有一段时间。