Ruby on Rails - Crontab 没有在 Ubuntu 14.04 上运行


  • 我在DigitalOcean VPS上遇到了一个关于set crontab Ubuntu 14.04的问题
  • 以下是我的步骤:
    • 首先,创建新的crontab:crontab -e
    • 第二,我设置了这个命令:

这是我的crontab,我设置它在每天上午10:26运行:

26 10 * * * /bin/bash -l -c 'cd /var/www/my_app/current && RAILS_ENV=production bundle exec rake check:user >> log/cron_log.log'
  • 第三,我将crontab检查为crontab -l
  • 最后,我将crontab重新启动为sudo service cron restart

但它无论如何都没有运行(我从10:24一直等到10:30(,我复制了这个命令并在控制台中运行,它运行得很好。

所以,我不明白为什么它不能像crontab一样运行。希望大家能解释一下或者给我一些建议。非常感谢。

编辑:我尝试使用gem whenever,但它没有运行。

set :environment, "production"
env :PATH, ENV['PATH']
env :GEM_PATH, ENV['GEM_PATH']
set :output, {:error => "log/cron_error_log.log", :standard => "log/cron_log.log"}
# Learn more: http://github.com/javan/whenever
every :day, at: '10:26am' do
  rake "check:user"
end

我更新了我的crontab use whether作为whenever -w但它不起作用。

更新:@Coderhs:我试着运行这个命令bundle exec whenever --update-crontab RAILS_ENV=production,但它不起作用:(.

这是我使用命令crontab -l:时列出的crontab

# Begin Whenever generated tasks for: RAILS_ENV=production
PATH=/var/www/my_app/shared/bundle/ruby/2.2.0/bin:/usr/local/rvm/gems/ruby-2.2.1/bin:/usr/local/rvm/gems/ruby-2.2.1@global/bin:/usr/local/rvm/rubies/ruby-2.2.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/local/rvm/bin
GEM_PATH=""
26 10 * * * /bin/bash -l -c 'cd /var/www/my_app/releases/20150710024713 && RAILS_ENV=production bundle exec rake user:check --silent >> log/cron_log.log 2>> log/cron_error_log.log'
# End Whenever generated tasks for: RAILS_ENV=production

它仍然没有运行。

更新:问题解决了。因为在我的本地时间不同于服务器时间。所以,我刚刚设置了服务器时间和我的本地时间相同。谢谢大家支持我。

如前所述,我会在任何时候使用gem。

确保在每次capistrano部署后再次运行wheny-w,以便查找正确的发布目录。

确保你在任何时候都以与你的应用程序相同的用户身份运行-w。除非你的应用以root身份运行,否则不要使用root。

此外,您应该在Capistrano部署配置中将日志目录设置为共享目录。config/deploy.rb:中有这样的内容

set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system', 'pids', 'public/uploads', 'public/temp')

还要在你的终端中运行"date"命令,看看时间是多少。这可能不是你的本地时间,所以cron可以工作,但时间与你预期的完全不同。

问题可能是因为运行cron的用户无法访问ruby命令"bundle"。您将不得不对crontab中的bundle可执行文件使用完整的bath。

对于这个问题,更好的解决方案是使用when-gemhttps://github.com/javan/whenever

它将管理所有与crontab相关的东西,以避免类似的问题。

schedule.rb用于

set :environment, "production"
set :output, {:error => "log/cron_error_log.log", :standard => "log/cron_log.log"}
env :PATH, ENV['PATH']
env :GEM_PATH, ENV['GEM_PATH']
     # Learn more: github.com/javan/whenever
every :day, at: '10:26am' do
  rake "check:user"
end

别忘了跑步。

bundle exec whenever --update-crontab RAILS_ENV=production

设置shedule.rb 之后

最新更新