Title
Cron Job doesnot run my Rails3 Cron tasks
Body

Yesterday, we got into an interesting scenario, Cronjobs were not working for our Deploy account. We use a separate user by name "deploy" which is used to run our Rails application. The deploy user is also configured to install and execute the capistrano scripts which installs the latest code and starts our phusion passenger server.

We had a write a Cron Task to run every 5 minitues and collect some information


As with any Rails guy, we wrote our Whenever scripts and installed in the server. but when we ran our whenever script, it created the cron task, but at that time, it didnot run.
 Our cronjob looked like below

> crontab -l

*/5 * * * * /var/www/myapp/current/script/rails runner -e production CronTask.every_5_mins  >> /var/www/myapp/shared/log/cronjob.log

However though this above task worked fine for us on the dev computers and on local servers, they didnot run on our server which is running the app under the "deploy" user.

To eliminate the scenario that crontab is not running on our server, we ran the below test

> crontab -l

*/5 * * * * /var/www/myapp/current/script/rails runner -e production CronTask.every_5_mins  >> /var/www/myapp/shared/log/cronjob.log
*/5 * * * * echo date  >> /var/www/myapp/shared/log/testcronjob.log

And after 5 minutes we saw that the our testcronjob.log started recieving the current date on to the log file. This eliminated our suspicion that cron is working fine... which leaves us that there could be an issue related to runner task not running under the deploy user. But the server is running fine. So we checked our passenger to identify what was the problem.
 

The solution lay down in our Passenger. where we found out that our ruby is running on /usr/local/bin/ruby instead or normal /usr/bin/ruby, which means my ruby is in /usr/local/bin.

Now the challenge was what to do to make this running
 

Solution 1: Modify the Crontab

*/5 * * * * /var/www/myapp/current/script/rails runner -e production CronTask.every_5_mins  >> /var/www/myapp/shared/log/cronjob.log

was modified to

*/5 * * * * bash -c "source /usr/local/bin/ruby" && /var/www/myapp/current/script/rails runner -e production CronTask.every_5_mins  >> /var/www/myapp/shared/log/cronjob.log

Solution 2: Modify the rails file

open your /script/rails file

on the first line replace which says

#!/usr/bin/env ruby

to

#!/usr/local/bin/ruby

In either case it works fine. We picked up option 2 as option 1 makes the cron dirty. However if you are not comfortable with solution2 you can always look at solution 1.

Once this is done your Crontasks will start working perfectly fine.

 

Associated Tags
ruby, rails, rails3, cron, cronjob, runner
Created By
admin
Created At
2011-09-24 06:51:58 UTC
Last Updated At
2011-09-24 06:51:58 UTC
Add Comment