Search code examples
ruby-on-rails-3croncron-taskrunner

rails-3 cron job not working with rails runner


Recently I came across the following tutorial of running cron job without using any Gems
http://www.ameravant.com/posts/recurring-tasks-in-ruby-on-rails-using-runner-and-cron-jobs

I create one file in /app/delete_old_posts.rb

  class DeleteOldPosts < ActiveRecord::Base          
    # This script deletes all posts that are over 5 minutes old          
     post_ids = Post.find(:all, :conditions => ["created_at < ?", 5.minutes.ago])          
     if post_ids.size > 0     
      Post.destroy(post_ids)     
      puts "#{post_ids.size} posts have been deleted!"       
     end       

Then create cron job by giving crontab -e command and in console of cronjob I wrote

*/2 * * * * /usr/bin/env ruby /home/abc/xyz/urjit.rajgor/workspace/thewall/rails/runner/home/XYZ/ABC/urjit.rajgor/workspace/thewall/app/delete_old_posts.rb          

cron job run after every two minutes but it did not work
Please help me.
Thanks


Solution

  • Try using the "whenever" gem. Allows you to define your cronjobs in ruby being able to specify rails runner, rake, or other custom wrappers and it handles writing the crontab for you. Makes life much simpler.

    Just add: gem 'whenever', :require => falseto your gemfile

    https://github.com/javan/whenever

    http://railscasts.com/episodes/164-cron-in-ruby