Rbenv and Cron

1 min read

In one of my projects, we are using the “whenever” gem for configuring cron. Also we were using Rbenv for Ruby version Management on the server.
We created the schedule.rb file with instructions to run a certain rake task every 5 mins as shown below.
[source language=”ruby”]
set :output, “log/production.log”
every 5.minutes do
rake “user:update”
end
[/source]
Then we installed the cron jobs using the command, whenever -i and this was the content of the crontab:
[source language="bash"]
# Begin Whenever generated tasks for: /home/ubuntu/apps/config/schedule.rb
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash -l -c 'cd /home/ubuntu/apps && RAILS_ENV=production bundle exec rake user:update --silent >> log/production.log 2>&1'
# end whenever tasks
[/source]
Everything seems good but then the jobs did not run and we got this error in the log - /bin/bash: bundle: command not found
Normally such an error comes when we don't have "Bundler". But we did have bundler already. We tried the command manually from the home directory - cd /home/ubuntu/apps && RAILS_ENV=production bundle exec rake user:update --silent >> log/production.log 2>&1 and it worked perfectly but this command would not work when ran with cron. This was very weird.
Then I came across a blog about this. The gentleman explained in the blog how our .bash_profile is not executed and hence rbenv would not be initialized when running commands from the cron.
So using the information we got from the blog I updated the crontab as below:
[source language="bash"]
# Begin Whenever generated tasks for: /home/ubuntu/apps/config/schedule.rb
0,5,10,15,20,25,30,35,40,45,50,55 * * * * export PATH=$HOME/.rbenv/bin:$PATH; eval "$(rbenv init -)"; cd /home/ubuntu/apps && RAILS_ENV=production bundle exec rake user:update --silent >> log/production.log 2>&1
# end whenever tasks
[/source]
And voila it worked! It's a nice thing to keep in mind when dealing with cron and rbenv in future. Hope this was useful.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *